【问题标题】:PHP how to set static variable from a stringPHP如何从字符串中设置静态变量
【发布时间】:2017-07-16 23:18:12
【问题描述】:

是否可以动态设置 php 静态类变量?在下面的示例中,我想将要设置的变量的字符串表示形式传递给函数“databaseInit”,然后该函数设置变量...

class app {
    static $database_smf;
    static $database_phpbb;

    /**
     * Initialise the app
     */
    static function init(){

        // No initialise the db connection
        self::databaseInit('database_phpbb');
        self::databaseInit('database_smf');

    }

    static function databaseInit( $database ){
        // is it possible to dynamically set the static var based on the param provided? eg:
        self::[$database] = true;
    }
}

【问题讨论】:

标签: php


【解决方案1】:

是的,这是可能的。 只需对您的代码稍作改动:

用途:

self::$$database = true;

代替:

self::[$database] = true;

class app {
    static $database_smf;
    static $database_phpbb;

完整代码:

    /**
     * Initialise the app
     */
    static function init(){

        // No initialise the db connection
        self::databaseInit('database_phpbb');
        self::databaseInit('database_smf');

    }

    static function databaseInit( $database ){
        // is it possible to dynamically set the static var based on the param provided? eg:
        self::$$database = true;
    }
}

【讨论】:

    【解决方案2】:

    您可以使用简单的变量变量名:

    static function databaseInit( $database ){
        self::$$database = true;
    }
    

    .. 但是你真的应该重新设计它,只保留一个数组并操作数组的键,因为这会将所有设置保留在一个命名空间中,而不是如果名称为其他静态变量可能会做奇怪的事情打错字等。

    class app {
        static $databases = [];
    
        ...
    
        static function databaseInit($database) {
            self::$databases[$database] = true;
        }
    }
    

    下一步将改为使类成为非静态类,这样可以更轻松地测试它并将其状态保持在本地。

    【讨论】:

    • 啊当然是的!变量变量!非常感谢!
    猜你喜欢
    • 2011-08-21
    • 1970-01-01
    • 2014-09-05
    • 2016-04-21
    • 2022-06-25
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    相关资源
    最近更新 更多