Why does the PHP object accept members that were only mentioned when called?

I am a paradox with the following piece of code and I am not sure how to call it.

I've defined a very simple class that doesn't have a variable yet. Now, in the constructor, I accept an array of keys and values ​​and assign variables on the fly like this using a foreach loop:

class Food{

    function Food($construct){
        foreach($construct as $key=>$value){
            $this->$key = $value;
        }

    }


}

      

If I created an instance now with input like so:

$food = new Food(array('name' => 'chicken' , 'unit' => 'kg' , 'calorie' => 10000));

      

I would get:

var_dump($food);    
object(Food)[1]
  public 'name' => string 'chicken' (length=7)
  public 'unit' => string 'kg' (length=2)
  public 'calorie' => int 10000

      

How is this possible?

+1


source to share


2 answers


This is possible in PHP and is the default implementation unless you specify otherwise (via __get () and __set ()). Creating public users on the fly is only possible for the current instance, but does not create one for the entire class. And this is possible from within the class or from the outside (for example, through an instance).

$food->smth = 100;

      

will create public smth

An empty magic method __set()

can prevent this behavior



public function __set($name, $value) { }

      

To the second question:

It's not safe, and using public users is generally unsafe (unless you have a really good reason to expose your properties). The agreement says that you must have mostly private / protected members with accessories for them. This way you can have a controll for a class from within the class and not from an instance. And for many other reasons, including code reuse.

+3


source


This variable is not uninitialized, it just isn't declared.

Declaring variables in a class definition is a style point for readability. Alternatively, you can set accessibility (private or public).



In any case, the declaration of variables clearly has nothing to do with OOP, it depends on the programming language. In Java, you cannot do this because the variables must be explicitly declared.

link - http://stackoverflow.com/questions/1086494/when-should-i-declare-variables-in-a-php-class

+2


source







All Articles