将属性添加到类实例

时间:2014-04-25 06:51:26

标签: php class

让我上课

class MyClass{
    //class implementation
}

我想在这个类中添加以下方法:

public function addProperty($property){
    //This method will be set a property of a current MyClass instance with the name **property** and the value **$property**
}

有没有想过实现这个方法?

3 个答案:

答案 0 :(得分:1)

  

此方法将设置当前MyClass实例的属性,其名称为 property ,值为 $ property

非常基本的,做:

public function addProperty($property){
  $this->property=$property;    // declare it as well
}

或者你的意思是属性只是一个占位符?然后你可以做

  $this->{$property}=$property; 

答案 1 :(得分:0)

public function addProperty($property){
    $this->{$property} = $property;
}

答案 2 :(得分:0)

只需在该类中编写该方法,为该类创建一个对象。如果您想使用该方法,只需使用该对象调用该方法

$obj = new MyClass; $return = $obj->addProperty();

在该方法中,如果你想使用属性,请按照明智的方式写下来

public function addProperty($property){
    $this->property = $property;
}

它将为您提供属性值

相关问题