implicit class variable declaration in php?

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.

Leave a Comment