How to create new property dynamically

前端 未结 4 1189
执念已碎
执念已碎 2020-12-04 09:51

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 c         


        
相关标签:
4条回答
  • 2020-12-04 10:03

    Use the syntax: $object->{$property} where $property is a string variable and $object can be this if it is inside the class or any instance object

    Live example: http://sandbox.onlinephpfunctions.com/code/108f0ca2bef5cf4af8225d6a6ff11dfd0741757f

     class Test{
        public function createProperty($propertyName, $propertyValue){
            $this->{$propertyName} = $propertyValue;
        }
    }
    
    $test = new Test();
    $test->createProperty('property1', '50');
    echo $test->property1;
    

    Result: 50

    0 讨论(0)
  • 2020-12-04 10:13

    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');
    
    0 讨论(0)
  • 2020-12-04 10:15

    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
    
    0 讨论(0)
  • 2020-12-04 10:20

    Property overloading is very slow. If you can, try to avoid it. Also important is to implement the other two magic methods:

    __isset(); __unset();

    If you don't want to find some common mistakes later on when using these object "attributes"

    Here are some examples:

    http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members

    EDITED after Alex comment:

    You can check yourself the differences in time between both solutions (change $REPEAT_PLEASE)

    <?php
    
     $REPEAT_PLEASE=500000;
    
    class a {}
    
    $time = time();
    
    $a = new a();
    for($i=0;$i<$REPEAT_PLEASE;$i++)
    {
    $a->data = 'hi';
    $a->data = 'bye'.$a->data;
    }
    
    echo '"NORMAL" TIME: '.(time()-$time)."\n";
    
    class b
    {
            function __set($name,$value)
            {
                    $this->d[$name] = $value;
            }
    
            function __get($name)
            {
                    return $this->d[$name];
            }
    }
    
    $time=time();
    
    $a = new b();
    for($i=0;$i<$REPEAT_PLEASE;$i++)
    {
    $a->data = 'hi';
    //echo $a->data;
    $a->data = 'bye'.$a->data;
    }
    
    echo "TIME OVERLOADING: ".(time()-$time)."\n";
    
    0 讨论(0)
提交回复
热议问题