PHP中的类字段和方法的工作原理 [英] Class fields and methods working principle in php

查看:75
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆