【问题标题】:PHP dynamic class names with static functions带有静态函数的 PHP 动态类名
【发布时间】:2015-08-20 22:37:05
【问题描述】:

我发现了一些奇怪的 PHP 行为,如果有人能解释我为什么这段代码的某些部分有效,而其他部分无效,我很感兴趣。

当类名存储在变量中时,PHP 可以动态创建新类。因为我使用的是现代版本的 PHP (5.5.28),所以它工作得很好。但是我发现了一些我不太了解的奇怪行为。

当类名存储在某个对象的属性中时会出现问题。在这种情况下,不能在动态类上调用静态函数: $this->dynClass::SomeFunction() 失败,($this->dynClass)::SomeFunction() 也失败。但是$instance = new $this->dynClass 有效。因此,如果我需要在$this->dynClass 上调用静态方法,我必须创建一个存储相同字符串的局部变量:$tmp = $this->dynClass。然后,我可以拨打$tmp::SomeFunction()

我真的不明白这一点。这可能是一个错误吗?请有人解释一下。

这是我的示例代码:

<?php
    class MyClass {
        static function SomeFunction($name){
            echo "Hello $name\n";
        }
    }

    MyClass::SomeFunction("World"); //Works fine as it should, prints Hello World

    $firstInstance = new MyClass;
    $firstInstance::SomeFunction("First"); //prints hello first, no problem

    //here comes the interesting part

    $dynClass = "MyClass";

    $dynClass::SomeFunction("Dynamic"); //Yeah, it works as well

    $secondInstance = new $dynClass;
    $secondInstance::SomeFunction("Second"); //Hello Second. Fine.

    //And here comes the part that I don't understand

    class OtherClass {
        private $dynClass = "MyClass";

        public function test(){

            $thirdInstance = new $this->dynClass; //WORKS!
            $thirdInstance::SomeFunction('Third'); //Hello Third

            //BUT

            $this->dynClass::SomeFunction("This"); //PHP Parse error:  syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)

            //OK, but then this one should work:

            ($this->dynClass)::SomeFunction("This"); //same error. WHY??

            //The only solution is creating a local variable:
            $tmp = $this->dynClass;
            $tmp::SomeFunction("Local"); //Hello Local

        }
    }

    $otherInstance = new OtherClass;
    $otherInstance->test();

?>

【问题讨论】:

  • 我不懂 php 内部原理,所以我不能告诉你确切的原因,但它看起来在 php 7 中已修复。使用当前 php7 beta 的实时示例:codepad.viper-7.com/CfJtD3 用于修复的 rfc:@ 987654322@

标签: php dynamic syntax static-functions


【解决方案1】:

在Uniform Variable Syntax之前,php的变量解析基本上是一大堆死角。

特别是,(...) 表达式不支持某些操作,例如 ::。

您遇到的两个错误是这种松散定义且不一致的变量解析器的示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多