【问题标题】:Calling static method from object array variable从对象数组变量调用静态方法
【发布时间】:2012-07-16 04:24:55
【问题描述】:

在 PHP 中,您可以像这样从对象实例(包含在数组中)调用类的静态方法:

$myArray['instanceOfMyClass']::staticMethod(); // works

但由于某种原因,当我使用 $this 变量时,我得到一个解析错误。例如:

$this->myArray['instanceOfMyClass']::staticMethod(); // PARSING ERROR

只是为了说明我的意思:

class MyClass{
    public static function staticMethod(){ echo "staticMethod called\n"; }
}

$myArray = array();
$myArray['instanceOfMyClass'] = new MyClass;
$myArray['instanceOfMyClass']::staticMethod(); // works

class RunCode
{
    private $myArray;

    public function __construct(){
        $this->myArray = array();
        $this->myArray['instanceOfMyClass'] = new MyClass;
        $this->myArray['instanceOfMyClass']::staticMethod(); // PARSING ERROR
    }
}

new RunCode;

关于如何解决这个问题的任何想法?

【问题讨论】:

  • static = 使用 self:: not $this->
  • 对不起?我不认为你明白我想要做什么。我只是想从 MyClass 的对象实例调用静态方法,这是 RunCode->myArray 中的一个条目。
  • 使用call_user_func(array($this->myArray['instanceOfMyClass'], 'staticMethod'));

标签: php arrays object static


【解决方案1】:

其实你可以使用“->”来调用静态方法:

$this->myArray['instanceOfMyClass']->staticMethod();

【讨论】:

  • 哦,哇,我从来没有意识到,谢谢。所以你只能使用 -> 来调用实例化对象上的静态方法?
  • 是的。这似乎很安全,因为您不能将同名的非静态方法添加到类中。
  • 为什么 PHP 必须如此反直觉?无论如何,谢谢你的提示。
【解决方案2】:

这是一个非常有趣的问题,它甚至可能是 PHP 本身的一个错误。

要解决这个问题,请使用 KISS 原则。

class RunCode
{
    private $myArray;

    public function __construct(){
        $this->myArray = array();
        $this->myArray['instanceOfMyClass'] = new MyClass;

        $instance = $this->myArray['instanceOfMyClass']
        $instance::staticMethod();
    }
}

希望这会有所帮助!

【讨论】:

  • 谢谢,是的,我想这是最简单的解决方案。我对 PHP 最大的不满是缺乏对您认为可行的语法的支持。例如。 $var = myFunction()[0]。你认为这值得提交一份错误报告吗?
【解决方案3】:

你将不得不使用一个临时变量来分解一个班轮,例如

$inst = $this->myArray['instanceOfMyClass'];
$inst::staticMethod()

这是许多 PHP 编译器不够聪明,无法理解嵌套表达式的情况之一。 PHP 开发人员最近一直在改进这一点,但仍有工作要做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多