在类中设置变量以用于多种功能/方法 [英] Set a variable in a class to be used on multiple functions/methods
本文介绍了在类中设置变量以用于多种功能/方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试设置一个 $ tester 变量,该变量可以在 MyClass 中的多个函数中使用。
I am trying to set a variable of $tester that can be used in multiple functions in MyClass.
我已经设置了变量并在 __ construct()
上添加了一个函数,但是当我试图将其回显时,却得到了未定义的变量通知-这是为什么?
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();
推荐答案
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();
尝试一下。始终称为 $ this->
的类中的属性。
对此文档
Try this. Properties in a class called always with $this->
.
Have a look on this documentation
这篇关于在类中设置变量以用于多种功能/方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文