How to create new property dynamically

前端 未结 4 1192
执念已碎
执念已碎 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: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)

    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";
    

提交回复
热议问题