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?
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
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).
will create
public smth
An empty
__set()
magic method can prevent this behaviorFor 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.