使用变量调用PHP静态方法



我在子名字空间('mynamespace'(下有各种PHP类('数字','字母顺序"等等(。我试图使用php变量(例如

(在子名称下调用这类各个类
    class ClassName {
        public static function foo ($MethodName) {
            //$MethodName has value “Numerical”
            //Normal Way of calling ‘Numerical’
            MyNamespaceNumerical::MyFunction();
            //What I want to do
            $variable = ‘MyNamespace$MethodName’;
                //OR
            $variable = “MyNamespace$MethodName”;
            $variable::MyFunction();    //Option-1 - This does not work
            {$variable}::MyFunction();  //Option-2 - This does not work
        } 
    }

从php 7开始,您可以使用以下语法:

$variable = "MyNamespace\".$MethodName."::MyFunction";
$variable();

检查3v4l.org以查看php> = 7.0和php&lt之间的差异;7.0

如果您不使用7.0版或更高版本的PHP,则无法使用此语法。您可以在变量函数上检查文档以获取更多信息。

您应该在代码中使用 '"(关于差异,请阅读http://php.net/manual/manual/en/language.types.string.php#language.types.types.types.types.string.string.syntax.syntax.single(。

检查一下:https://3v4l.org/cak7w

<?php
namespace MyNamespace {
    class Numerical {
        public static function MyFunction() {
            echo 'Called ', __FUNCTION__, '!', PHP_EOL;
        }
    }
}
namespace AnotherNamespace {
    class ClassName {
        public static function foo($MethodName) {
            /**
             * Two backslashes because of $ escapes to $ character and \ escapes to «backslash» itself
             * @see http://php.net/manual/en/language.types.string.php
             * @see http://php.net/manual/en/language.variables.variable.php
             * @see http://php.net/manual/en/functions.variable-functions.php
             */
            $variable = "\MyNamespace\${MethodName}"; // Option one works. 
            $variable::MyFunction();
        }
        public static function bar($className) {
            ('MyNamespace\' . $className)::MyFunction(); // Option two works in php version >= 7.1
        }
    }
    ClassName::foo('Numerical');
    ClassName::bar('Numerical');
}

php 7.1.0-7.2.4的输出:

Called MyFunction!
Called MyFunction!

最新更新