【发布时间】:2014-05-26 14:09:13
【问题描述】:
我正在尝试将函数分配为属性值。我写了以下代码:
class TestClass{
private $name;
public function __construct($name){
$this->$name=$name;
}
public function changeName($name){
$this->name=$name;
}
public function displayName(){
echo $this->name;
}
}
$testCls= new TestClass('Dmitry Fucintv');
$testCls->changeName=function($name){
$this->name='Other name';
};
$testCls->changeName('Some name');
$testCls->displayName();//Display 'Some name', but I'm expected that 'Other name' will be displayed.
问题:如何调用分配给字段的函数?
【问题讨论】:
-
@olaurendeau 此主题不重复。你能看懂我的问题吗?
-
哎呀对不起!我以为你想改变她的行为,你注意到你的 __construct() 方法是错误的吗?它应该是 $this->name=$name;
-
诀窍是“重新绑定 $this”,因为在您的示例中,新函数不知道您希望它成为对象的一部分。请注意,它仍然无法访问任何私有或受保护的属性,因此这种方法的功能有限。
标签: php class methods properties