Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create new property dynamically

How can I create a property from a given argument inside a object's method?

class Foo{    public function createProperty($var_name, $val){     // here how can I create a property named "$var_name"     // that takes $val as value?    }  } 

And I want to be able to access the property like:

$object = new Foo(); $object->createProperty('hello', 'Hiiiiiiiiiiiiiiii');  echo $object->hello; 

Also is it possible that I could make the property public/protected/private ? I know that in this case it should be public, but I may want to add some magik methods to get protected properties and stuff :)


I think I found a solution:
  protected $user_properties = array();    public function createProperty($var_name, $val){     $this->user_properties[$var_name] = $val;    }    public function __get($name){     if(isset($this->user_properties[$name])       return $this->user_properties[$name];    } 

do you think it's a good idea?

like image 354
Alex Avatar asked Jan 03 '12 02:01

Alex


People also ask

How do you add a dynamic property to an object?

Use an index signature to dynamically add properties to an object, e.g. const obj: {[key: string]: any} = {} .

How do you create a dynamic object?

You can create custom dynamic objects by using the classes in the System. Dynamic namespace. For example, you can create an ExpandoObject and specify the members of that object at run time. You can also create your own type that inherits the DynamicObject class.

How do you create a new property in an array?

Arrays are objects and therefore you can add your own properties to them: var arr = [1, 2, 3]; arr. foo = 'bar'; Extending from other answers, here are the following ways of iterating over the array, excluding custom properties.

Can we add dynamically named properties to JavaScript object?

So the best way of adding dynamically created property is the [bracket] method. Show activity on this post. Example: ReadValue("object.


2 Answers

The following example is for those who do not want to declare an entire class.

$test = (object) [];  $prop = 'hello';  $test->{$prop} = 'Hiiiiiiiiiiiiiiii';  echo $test->hello; // prints Hiiiiiiiiiiiiiiii 
like image 44
crownlessking Avatar answered Sep 23 '22 06:09

crownlessking


There are two methods to doing it.

One, you can directly create property dynamically from outside the class:

class Foo{  }  $foo = new Foo(); $foo->hello = 'Something'; 

Or if you wish to create property through your createProperty method:

class Foo{     public function createProperty($name, $value){         $this->{$name} = $value;     } }  $foo = new Foo(); $foo->createProperty('hello', 'something'); 
like image 181
mauris Avatar answered Sep 25 '22 06:09

mauris