How to create new property dynamically

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

提交回复
热议问题