So I ran into a problem while building a class in which I was unable to set the property of the class directly, and instead had to set it during construction. Here is an example of what I was trying to do.
class foo
{
private $con = Db::init();
public function __construct()
{
}
//continue class..
}
As you can see, I am just assigning a simple singleton PDO class to the property. This does not work, and I am forced to do the following.
class foo
{
private $con;
public function __construct()
{
$this->con = Db::init();
}
//continue class..
}
The开发者_如何学编程 first approach does not report any errors either. It just fails to continue execution. Any thoughts?
edit
The lack of errors may also be a Zen Cart thing.
What is happening here is the class is a structure, and the structure is compiled before your PHP Fiel is executed, as in the compile time PHP Does not instantiate any dynamic data, you cannot use dynamic data.
For example:
$function = 'hello';
function $function(){}
Within the compile time the variable '$function' does not exists so it cannot be read, within your class PHP Has provided a function called __construct
which is fired within run-time, meaning that the rest of the system's dynamic data is available.
class foo
{
protected $bar;
public function __construct()
{
$this->bar = Db::Init();
}
}
So the process is:
- Compile Time
- Class foo
- variable bar
- function __construct
- Run Time
- new foo found
- internally create object
- execute foo::__construct()
- return foo
That's a simplified version of the process, there are some several ways to set objects to a class, you can do the regular approach as shown above
you can inject by doing:
public function __construct(Bar $bar)
{
$this->bar = $bar;
}
you can create a base class and extend:
class DatabaseAccess
{
protected $db;
public function __construct()
{
$this->db = Db::Init();
}
}
and then do:
class User extends DatabaseAccess
{
public function getUser($id)
{
$this->db->fetchRow('users',$id);
}
}
}
Please see the class property docs at http://www.php.net/manual/en/language.oop5.properties.php
... 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.
Db::init()
must be evaluated at run time to determine the value to set the private $con
, which conflicts with the compile time requirement of class properties.
精彩评论