Implicit declaration of a class variable in php?

I was looking at some code and it is difficult for me to work with variable declaration in php classes. In particular, it seems that the code I'm looking at does not declare class variables before it uses them. Now this can be expected, but I can not find information that this is possible. So you would expect this:

class Example
{

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

    }

}

work? and does it create these variables in an instance of the class that will be used in the future?

+2
source share
3 answers

This works the same as declaring a normal variable:

$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 must be specified as part of the class declaration. PHP class members can be created at any time.

, public $foo = null; , , .

+3

: ( ) ?
. ( , ++), . . 2 , . http://www.php.net/manual/en/language.oop5.basic.php , E_STRICT.

, ?

. PHP Fun? ++/#, PHP , , .

+2

This is fully functional, although opinions will vary. Since the creation of member variables of the class in the constructor, they will exist in each instance of the object, if not deleted.

It is conditional to declare member variables of the class 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';
    }
}
+1
source

All Articles