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

2019-09-05 19:16发布

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();

标签: php class oop
1条回答
再贱就再见
2楼-- · 2019-09-05 19:47
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

查看更多
登录 后发表回答