So for example I have this code:
class Object{
public $tedi;
public $bear;
...some other code ...
}
Now as you can see there are public variables inside this class. What I would like to do is to make these variables in a dynamic way, with a function something like:
private function create_object_vars(){
// The Array what contains the variables
$vars = array("tedi", "bear");
foreach($vars as $var){
// Push the variables to the Object as Public
public $this->$var;
}
}
So how should I create public variables in a dynamic way?
You assign an object to such a variable by placing the object after the equal sign ( = ) in an assignment statement or initialization clause.
In PHP, an object variable doesn't contain the object itself as value. It only contains an object identifier which allows object accessors to find the actual object.
To create an Object in PHP, use the new operator to instantiate a class. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created.
We can create an object without creating a class in PHP, typecasting a type into an object using the object data type. We can typecast an array into a stdClass object. The object keyword is wrapped around with parenthesis right before the array typecasts the array into the object.
$vars = (object)array("tedi"=>"bear");
or
$vars = new StdClass();
$vars->tedi = "bear";
Yes, you can do this.
You're pretty much correct - this should do it:
private function create_object_vars(){
// The Array of names of variables we want to create
$vars = array("tedi", "bear");
foreach($vars as $var){
// Push the variables to the Object as Public
$this->$var = "value to store";
}
}
Note that this makes use of variable variable naming, which can do some crazy and dangerous things!
As per the comments, members created like this will be public - I'm sure there's a way of creating protected/private variables, but it's probably not simple (eg you could do it via the C Zend API in an extension).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With