在 class 中绕过 setter
Getting around setters inside class
所以当我必须绑定变量以在我的函数中使用时,我刚刚开始使用魔术方法和 运行 来解决这个问题。
这是我的问题的一个小例子
class test{
protected $arraytest = array();
function __construct(){
$this->test = "datafor2";
var_dump($this->arraytest);
}
function test(){
return $this->test;
}
function __set($name, $value){
$this->arraytest[$name] = $value;
}
}
$test = new test();
echo $test->test();
所以我想做的是绑定 test
以便以后在函数 test()
中使用,但是因为我将变量绑定到对象,所以它使用魔术方法并相应地绑定它到 setter。
这不是我正在寻找的行为,因为变量 $arraytest
不应该绑定变量 test
。
有什么方法可以解决?我知道如果变量是 test
,我可以在 stter 中做一个例外,只是想知道在使用 magic setters.
时有什么更好的做法
只需将变量声明为属性,setter将不会被使用。
class test{
protected $arraytest = array();
protected $test;
function __construct(){
$this->test = "datafor2";
var_dump($this->arraytest);
}
function test(){
return $this->test;
}
function __set($name, $value){
$this->arraytest[$name] = $value;
}
}
$test = new test();
echo $test->test();
所以当我必须绑定变量以在我的函数中使用时,我刚刚开始使用魔术方法和 运行 来解决这个问题。
这是我的问题的一个小例子
class test{
protected $arraytest = array();
function __construct(){
$this->test = "datafor2";
var_dump($this->arraytest);
}
function test(){
return $this->test;
}
function __set($name, $value){
$this->arraytest[$name] = $value;
}
}
$test = new test();
echo $test->test();
所以我想做的是绑定 test
以便以后在函数 test()
中使用,但是因为我将变量绑定到对象,所以它使用魔术方法并相应地绑定它到 setter。
这不是我正在寻找的行为,因为变量 $arraytest
不应该绑定变量 test
。
有什么方法可以解决?我知道如果变量是 test
,我可以在 stter 中做一个例外,只是想知道在使用 magic setters.
只需将变量声明为属性,setter将不会被使用。
class test{
protected $arraytest = array();
protected $test;
function __construct(){
$this->test = "datafor2";
var_dump($this->arraytest);
}
function test(){
return $this->test;
}
function __set($name, $value){
$this->arraytest[$name] = $value;
}
}
$test = new test();
echo $test->test();