Gogol Gogol - 1 year ago 51
PHP Question

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

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:

public 'name' => string 'chicken' (length=7)
public 'unit' => string 'kg' (length=2)
public 'calorie' => int 10000

How is this even possible?

Answer Source

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.