Consistent use of PHP OOP properties
I am really new to OOP. I'm not even a beginner, I'm a nob. So. I want to port my pseudo-CMS from "normal" programming to an OOP programming system. So:
private static $dsn = DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME;
What is causing the problem here? Using restrictions? I dont know. My editor (aptana studio) is showing error after 1 constant. Thanks to
Edit:
Thanks for your quick response. I will do it in contructor.
Edit2:
But what if I want to use a singleton? How do I pass arguments to contructor?
a source to share
See documentation :
This declaration may include initialization, but this initialization must be a constant value, that is, it must be capable of being evaluated at compile time and must not depend on run-time information for evaluation.
You cannot concatenate strings when defining class properties.
An example from the documentation (for completeness):
<?php
class SimpleClass
{
// invalid property declarations:
public $var1 = 'hello ' . 'world';
public $var2 = <<<EOD
hello world
EOD;
public $var3 = 1+2;
public $var4 = self::myStaticMethod();
public $var5 = $myVar;
// valid property declarations:
public $var6 = myConstant;
public $var7 = array(true, false);
// This is allowed only in PHP 5.3.0 and later.
public $var8 = <<<'EOD'
hello world
EOD;
}
?>
When switching to OOP, you shouldn't use constants anyway. Pass these values to your class constructor:
public function __construct($db_type, $db_host, $db_name) {
self::$dsn = $db_type.':host='.$db_host.';dbname='.$db_name;
}
a source to share
The problem is that properties have to be inline constants when you put them in initializer fields.
What you are doing won't work, but it will, for example:
private static $dsn = 'mysql:host=localhost;dbname=mydb';
I know this is silly, but you can't even use PHP constants. You should literally have it in plain text.
The solution to this is initialization $dsn
in the class constructor, for example:
class MyClass
{
public function __construct()
{
self:: $dsn = DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME;
}
}
a source to share