加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

使用PHP 5.3中的实例方法的奇怪结果

发布时间:2020-12-13 17:10:27 所属栏目:PHP教程 来源:网络整理
导读:想知道下面的例子是如何实际工作的,以及如何能够动态地做这样的事情.使用call_user_func或call_user_func_array不允许这种情况发生. ?phpclass Person{ public $name = "George"; public function say_hi() { return ExtraMethods::hi(); }}class ExtraMetho
想知道下面的例子是如何实际工作的,以及如何能够动态地做这样的事情.使用call_user_func或call_user_func_array不允许这种情况发生.

<?php
class Person
{
    public $name = "George";

    public function say_hi()
    {
            return ExtraMethods::hi();
    }
}

class ExtraMethods
{
    public function hi()
    {
            return "Hi,".$this->name;
    }
}

$george = new Person();
echo $george->say_hi();
?>

这应该导致:

Hi,George

想知道为什么实例方法hi不仅可以静态调用(不会感到惊讶,这可能发生在PHP中),但为什么我能够使用$this

解决方法

从 manual:

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs,but possibly another object,if the method is called statically from the context of a secondary object).

所以,根据第二部分,按设计.请记住它虽然使用了实际的对象实例(换句话说,如果你添加public $name =“SomethingElse”;对于ExtraMethods,结果仍然是Hi,George).

静态调用该方法不是正确的编码,但PHP会原谅您,并且只发出严格错误:

"Strict Standards: Non-static method ExtraMethods::hi() should not be called statically,assuming $this from incompatible context in ..."

当然,在这种情况下,只是将对象作为参数传递将更加清晰和可取.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读