How to create new property dynamically

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

提交回复
热议问题