implicit class variable declaration in php?

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?


Solution 1:

This works the same as a normal variable declaration would work:

$foo = 'bar'; // Created a new variable

class Foo {
    function __construct() {
        $this->foo = 'bar'; // Created a new variable
    }
}

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.

Solution 2:

So would you expect this: (code sample) to work?
Yes. It's pretty bad practice (at least it makes my C++ skin crawl), but it wouldn't surprise me in the slightest. See example 2 in the following page for an example of using another class without declaring it beforehand. http://www.php.net/manual/en/language.oop5.basic.php It will throw an error if E_STRICT is enabled.

And does this create these variables on the class instance to be used hereafter?

Yep. Ain't PHP Fun? Coming from a C++/C# background, PHP took a while to grow on me with its very loose typing, but it has its advantages.

Solution 3:

That's completely functional, though opinions will differ. Since the creation of the class member variables are in the constructor, they will exist in every instance of the object unless deleted.

It's conventional to declare class member variables with informative comments:

class Example
{
    private $data;  // array of example data

    private $var;   // main state variable

    public function __construct()
    {
        $this->data = array();
        $this->var = 'something';
    }
}