英文:
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'])
returnB
? - 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论