【问题标题】:Class fields and methods working principle in phpphp中的类字段和方法工作原理
【发布时间】: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


【解决方案1】:

将函数分配给属性后,对象有一个名为changeName方法 和一个名为changeName属性。那么->changeName() 指的是哪个?是($testCls->changeName)() 还是($testCls->changeName())?答案是现有方法胜出。您不能以这种方式覆盖或替换方法。

你可以这样调用属性函数:

call_user_func($testCls->changeName, 'Some name');

但是,这会抛出这个错误:

Fatal error: Using $this when not in object context

因为您分配的匿名函数内部的$this 没有引用$testCls,所以它没有引用任何内容,因为在定义函数的范围内没有$this

换句话说,这根本不会像你想要的那样工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 2014-09-16
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多