【问题标题】:PHP Class Scope confusing with call_user_func()PHP 类范围与 call_user_func() 混淆
【发布时间】:2014-02-15 17:32:39
【问题描述】:
class A
{
    public static function who1()
    {
        var_dump(get_called_class());
    }
}
class B extends A
{
    public static function who2()
    {
        parent::who1();
    }
}
call_user_func(array('B', 'parent::who1'));
B::who2();

我的期望:

string 'B' (length=1)

string 'B' (length=1)

实际回报:

boolean false

string 'B' (length=1)

谁能告诉我为什么输出与我的预期不同?

另见:

http://us1.php.net/manual/en/language.types.callable.php

http://us1.php.net/manual/en/function.get-called-class.php

编辑: 也许我的旧代码不清楚,这是新的例子:

class A
{
    public static function who()
    {
        var_dump(get_called_class());
    }
}
class B extends A
{
    public static function who()
    {
        echo 'hehe';
    }
}
call_user_func(array('B', 'parent::who'));

为什么会输出假?

【问题讨论】:

  • 您不需要在对parent::who1 的调用中添加parent 部分。看看php.net/manual/en/language.oop5.inheritance.php:For example, when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.
  • 不要使用parent:::call_user_func(array('B', 'who1'));

标签: php class scope


【解决方案1】:

来自PHP manual documentation for Object Inheritance:

例如,当您扩展一个类时,子类会继承父类的所有公共和受保护方法。除非类覆盖这些方法,否则它们将保留其原始功能。

如上所述,call_user_func() 中不需要parent 前缀:

call_user_func(array('B', 'who'));

你在var_dump() 中得到了FALSE,因为call_user_func() 声明了类外部的方法调用。所以get_called_class() 的行为符合预期(或手册中提到的):

如果从类外部调用,则返回 FALSE。

【讨论】:

  • 我不明白。 get_call_class() 仍然在方法 who() 中,who() 在类 A 中。如果我这样称呼它 A::who();它将输出 A。
  • @nut get_called_class() 在这种情况下可能无法正确确定调用者类。这对我来说似乎是一个错误。看起来 call_user_func(array('B', 'parent::who')); 强制 ::who() 在类范围之外被调用。
  • 是的,我的例子看起来很复杂,我会把它贴在错误列表上以获取详细信息。并感谢提及对象继承
猜你喜欢
  • 2011-12-22
  • 1970-01-01
  • 1970-01-01
  • 2016-02-24
  • 1970-01-01
  • 2020-02-16
  • 2015-03-29
  • 1970-01-01
  • 2016-10-09
相关资源
最近更新 更多