Is it possible to define attributes to a class in the constructor. For instance I pass a Associative Array to a class constructor and I want the attributes to that class to be declared and set based on what is in the Associative Array.
TIA
Is it possible to define attributes to a class in the constructor. For instance I pass a Associative Array to a class constructor and I want the attributes to that class to be declared and set based on what is in the Associative Array.
TIA
class Foo{
function __construct($arr){
foreach($arr as $k => $v)
$this->$k = $v;
}
}
You can review the constructor/desctructor manual and properties manual.
to be noted since you don't define the properties in the class all are set to public which IMHO is kind of dangerous. I think it might be possible to achieve the same thing using the reflection. I just checked more in depth the reflection and it is not possible (with PHP5), since it would make sense to be able to do that from the reflection it might come with PHP6.
full sample
<?php
class Foo{
function __construct($arr){
foreach($arr as $k => $v)
$this->$k = $v;
}
function getBar(){
return $this->bar;
}
}
$bar = new Foo(array(
'bar' => 'bar',
'foo' => 'foo'
)
);
var_dump($bar->bar);
?>
You can certainly do this, as RageZ describes above, but I don't think I would recommend doing it. What this does is creates too loose of a "contract" between the users of this class - i.e. nobody really knows which properties the class has.
Instead of defining the properties on the fly, I would bet that you have a pre-defined set of "object property sets" that could in turn define a class hierarchy.
So instead of doing
Do this:
Then, use the Factory pattern to generate the right type of object depending on the parameters passed to the static factory method.