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

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条回答 默认 最新

相关推荐 更多相似问题