无法理解使用call_user_func的PHP代码片段。

huangapple go评论64阅读模式
英文:

Can't understand PHP code snippet using call_user_func

问题

  • 为什么 call_user_func(['parent', 'bar']) 返回 B
  • ['parent', 'bar'][parent::class, 'bar'] 之间有什么区别?

请注意,我将保留代码部分不翻译,只回答你的问题。

英文:

Here is the snippet:

class A
{
    static function bar()
    {
        echo get_called_class(), "\n";
    }

}


class B extends A
{
    static function foo()
    {
        call_user_func(['parent', 'bar']);// B why?
        call_user_func([parent::class, 'bar']); // A
        call_user_func(parent::class . '::bar');// A

    }

}
  • Why does call_user_func(['parent', 'bar']) return B?
  • What is the difference between ['parent', 'bar'] and [parent::class, 'bar']?

答案1

得分: 0

有了最新的PHP版本,您可能会看到这个弃用消息:

弃用:在可调用函数中使用“parent”已弃用

关于弃用的更多详细信息可以在这里找到:

我觉得这不容易回答,但我理解的方式是:因为“parent”只是一个字符串,并且是一个通用名称,它的意义(具体的类)取决于上下文。

我怀疑get_called_class()因此与它不兼容,不能像您期望的

英文:

With the latest PHP version you may see this deprecation message:

> Deprecated: Use of "parent" in callables is deprecated

And some more details of the deprecation you can find already here:

I don't find this easy to answer, but this is how I understand it: As "parent" is a string only and a generic name its meaning (which concrete class) depends on context.

I suspect get_called_class() is therefore incompatible with it and can't resolve the class context as you have expected it.

When you use parent::class PHP can resolve the context properly to the concrete class name, therefore using it with call_user_func() does not have this ambiguity or context problem.

huangapple
  • 本文由 发表于 2023年2月10日 14:43:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75407716.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定