Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to Create Object Variables?

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?

like image 533
Adam Halasz Avatar asked Dec 05 '10 10:12

Adam Halasz


People also ask

How do you create an object variable?

You assign an object to such a variable by placing the object after the equal sign ( = ) in an assignment statement or initialization clause.

What is an object variable in PHP?

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.

How will you create objects in PHP?

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.

Can we create object without class in PHP?

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.


2 Answers

$vars = (object)array("tedi"=>"bear");

or

$vars = new StdClass();
$vars->tedi = "bear";
like image 181
bfg9k Avatar answered Oct 18 '22 02:10

bfg9k


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).

like image 43
John Carter Avatar answered Oct 18 '22 02:10

John Carter