Set a variable in a class to be used on multiple f

2019-09-05 19:31发布

问题:

I am trying to set a variable of $tester that can be used in multiple functions in MyClass.

I have set the variable and added a function on __construct() but I am getting an undefined variable notice when I try to echo it out - why is this?

    class MyClass {

        public $tester;

        public function __construct() {
            add_action( 'init', array( &$this, 'variables' ) );
            add_action( 'init', array( &$this, 'do_stuff' ) );
        }

        public function variables() {
            $tester = get_option( 'an_option' );
        }

        public function do_stuff() {
            echo $tester;
        }

    }

    $my_class   =   new MyClass();

回答1:

class MyClass {

    public $tester;

    public function __construct() {
        add_action( 'init', array( &$this, 'variables' ) );
        add_action( 'init', array( &$this, 'do_stuff' ) );
    }

    public function variables() {
        $this->tester = get_option( 'an_option' );
    }

    public function do_stuff() {
        echo $this->tester;
    }

}

$my_class   =   new MyClass();

Try this. Properties in a class called always with $this->.
Have a look on this documentation



标签: php class oop