Class fields and methods working principle in php

2019-02-28 21:52发布

问题:

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:

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.