【问题标题】:Call PHP Static Method using variable使用变量调用 PHP 静态方法
【发布时间】:2018-04-02 12:55:16
【问题描述】:

我在子命名空间(“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
        } 
    }

【问题讨论】:

  • 您使用的是哪个版本的 PHP?

标签: php class static


【解决方案1】:

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

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

检查 3v4l.org 以查看 PHP >= 7.0 和 PHP

如果您使用的不是 7.0 或更高版本的 PHP,则不能使用此语法。您可以查看documentation on variable functions了解更多信息。

【讨论】:

  • 嗨。我试过。结果如下: Validation\App::AppControl(); //这是有效的。 $nameSpace = "验证"; $var = $nameSpace."\\App::AppControl"; $var(); //这不起作用。错误 = 找不到类“Validation\App”
  • @Krishna 那是因为您忘记将所需的“\”放在命名空间之前。 $nameSpace = "\Validation" 应该可以工作。它找不到类 Validation\App,因为在您当前的命名空间(默认命名空间)中没有类 Validation\App。
【解决方案2】:

您应该在代码中使用' 或"(关于差异请阅读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!

【讨论】:

    猜你喜欢
    • 2017-04-16
    • 2010-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 2015-09-14
    相关资源
    最近更新 更多