PHP中的类字段和方法的工作原理 [英] Class fields and methods working principle in php
问题描述
我正在尝试将一个函数分配为属性值.我编写了以下代码:
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?
推荐答案
将功能分配给属性后,对象具有称为changeName
的方法和属性称为changeName
.那么->changeName()
指的是什么?是($testCls->changeName)()
还是($testCls->changeName())
?答案是现有方法胜出.您不能以这种方式覆盖或替换方法.
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
因为在您分配的匿名函数内的$this
并未引用$testCls
,所以它什么也没有引用,因为在定义该函数的范围内没有$this
.
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.
这篇关于PHP中的类字段和方法的工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!