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:
Within the compile time the variable ‘$function’ does not exists so it cannot be read, within your class PHP Has provided a function called
__constructwhich is fired within run-time, meaning that the rest of the system’s dynamic data is available.So the process is:
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:
you can create a base class and extend:
and then do:
}