是否可以使以下bar()方法返回“蓝色”?
class TestClass
{
public $var1 = "red";
public function foo() //returns red
{
return $this->var1;
}
public function bar() //still returns red
{
$this->var1 = "blue";
return $this->var1;
}
}
我知道类属性不能是变量,加法结果等。我读过使用__set和__get的重载,但这似乎是针对完全动态的属性。
答案 0 :(得分:3)
您的代码目前可以按照您的描述运行。从PHP交互式shell:
php > $t = new TestClass();
php > echo $t->foo();
red
php > echo $t->bar();
blue
php > echo $t->foo();
blue
也许你可以用不同的方式解释你的问题?
答案 1 :(得分:0)
您可以使用可选参数将bar()方法更新为设置栏。
公共功能栏($ mycolor ='red') { $ this-> var1 = $ mycolor; 返回$ this-> var1; }