While making the static class for database getting this error
开发者_JAVA技巧Here is my class
class Databases {
public $liveresellerdb = new Database('1host1','user','pswd','db');
}
the error i am getting is
Parse error: syntax error, unexpected T_NEW in /home/abhijitnair/sandbox/newreseller/Databases.php on line 33
why this error is coming?
Properties may not be preset with runtime information.
Quoting PHP Manual:
Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
<?php
class Databases {
public static $liveresellerdb;
}
Databases::$liveresellerdb = new Database('1host1','user','pswd','db');
?>
This is how you initialise a static member...
Because you forgot to write the static
keyword to actually make the property static.
In addition, you can't initialise static properties with expressions like this. Here's a workaround.
you cannot assign object during the class preperation stages, only the class instantation:
class Databases
{
public $liveresellerdb;
public function __construct()
{
$this->liveresellerdb = new Database('1host1','user','pswd','db');
}
}
anything within the constructor can be generic PHP code, outside the function and instead the class body has specific laws.
if you require the database's to be static then you have to set / access them differently.
class Databases
{
public static $liveresellerdb;
}
Databases::liversellerdb = new Database('1host1','user','pswd','db');
精彩评论