使用变量调用PHP静态方法

时间:2018-04-02 12:55:16

标签: php class static

我在子命名空间('MyNamespace')下有各种PHP类('Numerical','Alphabetical'等)。我试图使用像

这样的php变量在子命名空间下调用这个各种类
    class ClassName {
        public static function foo ($MethodName) {

            //$MethodName has value “Numerical”
            //Normal Way of calling ‘Numerical’
            MyNamespace\Numerical::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
        } 
    }

2 个答案:

答案 0 :(得分:0)

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

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

检查3v4l.org以查看PHP> = 7.0和PHP<之间的区别7.0

如果您没有使用7.0或更高版本的PHP,则无法使用此语法。您可以查看documentation on variable functions以获取更多信息。

答案 1 :(得分:0)

您应该在代码中使用'"(关于差异阅读http://php.net/manual/en/language.types.string.php#language.types.string.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!
相关问题