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

发布于 2024-12-26 10:00:55 字数 589 浏览 0 评论 0原文

想知道下面的示例实际上是如何工作的,以及如何能够动态地执行类似的操作。使用 call_user_funccall_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 >

Wondering how the example below is actually working, and how one would be able to do something like dynamically. Using call_user_func or call_user_func_array doesn't allow this to happen.

<?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();
?>

this should result with:

Hi, George

Wondering why the instance method hi can be called not only statically (not surprised that this can happen in PHP), but why I am able to use $this

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝戈者 2025-01-02 10:00:55

来自手册

当从对象上下文中调用方法时,伪变量 $this 可用。 $this 是对调用对象的引用(通常是该方法所属的对象,但也可能是另一个对象,如果该方法是从辅助对象的上下文中静态调用的)。

因此,根据第二部分,按照设计。请记住,它使用现有的实际对象实例(换句话说,如果将 public $name = "SomethingElse"; 添加到 ExtraMethods,结果仍然是嗨,乔治)。

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

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

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

From the 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).

So, according to the second portion, by design. Keep in mind it uses the actual object instance in existance though (in other words, if you add public $name = "SomethingElse"; to ExtraMethods, the result would still be Hi, George).

Calling the method statically is not proper coding, but PHP forgives you, and issues only a Strict Error:

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

Of course, in this instance, just passing the object as an argument would be far clearer and preferable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文