du8794 2017-01-12 11:46
浏览 15
已采纳

在类中设置一个变量以用于多个函数/方法

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

  • dongyumiao5210 2017-01-12 11:50
    关注
    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

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部