I’ve been looking at some code and am having a hard time working out variable declaration in php classes. Specifically it appears that the code i’m looking at doesn’t declare the class variables before it uses them. Now this may be expected but I can’t find any info that states that it is possible. So would you expect this:
class Example
{
public function __construct()
{
$this->data = array();
$this->var = 'something';
}
}
to work? and does this create these variables on the class instance to be used hereafter?
This works the same as a normal variable declaration would work:
PHP classes are not quite the same as in other languages, where member variables need to be specified as part of the class declaration. PHP class members can be created at any time.
Having said that, you should declare the variable like
public $foo = null;in the class declaration, if it’s supposed to be a permanent member of the class, to clearly express the intent.