Why does a PHP object accept members that were onl

2019-08-01 06:24发布

I am in a paradox with the following code snippet and I am not sure what to call it.

I have defined a very simple class which has no variable yet. Now, in the constructor, I am accepting an array of keys and values and assigning 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 the input like so:

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

I would have got:

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 even possible?

标签: php oop
2条回答
劳资没心,怎么记你
2楼-- · 2019-08-01 06:52

That variable isn't uninitialized, it's just undeclared.

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

Anyway, declaring variables explicitly has nothing to do with OOP, it's programming-language-specific. In Java you can't do that because variables must be declared explicitly.

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

查看更多
太酷不给撩
3楼-- · 2019-08-01 07:02

This is possible in PHP and is the default implementation unless you have stated otherwise (via __get() and __set()). Creating public members on the fly is possible only for the current instance, it does not create it for the class overall. And it's possible from inside the class or from outside (e.g. via the instance).

$food->smth = 100;

will create public smth

An empty __set() magic method can prevent this behavior

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

For the second question:

It is not safe and using public members at all is not safe (unless you have really good reason for exposing your properties). The convention says you have to have mostly private/protected members with accessors for them. So you can have the controll for the class from inside the class rather than from the instance of it. And for many other reasons, including code reusability.

查看更多
登录 后发表回答