dsy1971 2016-09-23 04:08
浏览 85
已采纳

PHP:在类中设置一个全局变量

In a PHP class, is there a way to set set a global variable that doesn't need to be called in each function?

For example, I have a variable called $settings which contains an array of values:

Array( [option_1] => on, [option_2] => on, [option_3] => off )

The get_option() function comes from WordPress. The values in the $settings array determine which functions to run:

class My_Class {

    public function __construct() {
        # Get array of options
        $settings = get_option( 'my_options' );

        if ( is_array( $settings ) || is_object( $settings ) ) {
            if ( $settings['option_1'] == 'on' ) {
                add_action( 'tag_1', array( $this, 'function_1' ) );
            }

            if ( $settings['option_2'] == 'on' ) {
                add_action( 'tag_2', array( $this, 'function_2' ) );
            }
        }
    }

    public function function_1() {
        # Call the array of options again
        $settings = get_option( 'my_options' );

        echo 'This option is ' . $settings['option_1'];
    }

    public function function_2() {
        # Code here...
    }

new My_Class();

However, I call the following line twice in my __construct() and function_1():

$settings = get_option( 'my_options' );

Instead of calling this variable twice in two different functions, what's the proper way of calling the same variable which can be used within different functions of my class? I tried adding the $settings variable function just below the class My_Class, but that didn't work:

class My_Class {

    global $settings = get_option( 'my_options' );
    # Rest of the code below...
  • 写回答

1条回答 默认 最新

  • dongxinjun3944 2016-09-23 04:14
    关注

    You can declare $settings as a class property

    protected $settings;
    

    Then inside __construct

    $this->settings = get_option( 'my_options' );
    

    You can then access it anywhere inside the class using $this->settings

    public function function_1() {
        echo 'This option is ' . $this->settings['option_1'];
    }
    

    For more details about properties, you can refer to PHP documentation http://php.net/manual/en/language.oop5.properties.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料