Class fields and methods working principle in php

前端 未结 1 1274
北恋
北恋 2021-01-24 20:01

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         


        
相关标签:
1条回答
  • 2021-01-24 20:47

    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.

    0 讨论(0)
提交回复
热议问题