Class fields and methods working principle in php

2019-02-28 22:23发布

I'm trying to assign a function as a property value. I've written the following code:

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.

Question: How can I invoke a function which is assigned to a field?

1条回答
爷的心禁止访问
2楼-- · 2019-02-28 22:35

After assigning the function to the property, the object has a method called changeName and a property called changeName. Which then does ->changeName() refer to? Is it ($testCls->changeName)() or ($testCls->changeName())? The answer is that the existing method wins out. You cannot overwrite or replace a method this way.

You can call the property function like this:

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

However, this will throw this error:

Fatal error: Using $this when not in object context

Because $this inside the anonymous function you assigned does not refer to $testCls, it refers to nothing, since there is no $this in the scope where the function was defined.

In other words, this won't work at all the way you want it to.

查看更多
登录 后发表回答