2011-03-16 36 views
0

是否有可能使下面的bar()方法返回“蓝色”?PHP类别变量重新分配

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超载,但似乎对完全动态性能为目标。

+8

它确实[返回蓝色](http://ideone.com/t2Tla)? –

+0

上面在PHP 3.5.3中为我返回“蓝色”,当我按照'$ t = new TestClass; echo $ t-> bar();'。你怎么叫'bar()'?由于'$ var1'是非静态的,它是一个实例属性而不是类属性。 –

+1

我认为你的意思是5.3.3?或者你有一个helluva旧版本的PHP大卫=) – PatrikAkerstrand

回答

3

您的代码目前正如您所描述的那样工作。从PHP交互式外壳:

php > $t = new TestClass(); 
php > echo $t->foo(); 
red 
php > echo $t->bar(); 
blue 
php > echo $t->foo(); 
blue 

也许你可以用不同的方式解释你的问题?

+0

同样适合我,工作完美,我看不出为什么它不应该 –

+0

感谢您的答复。我得到了它的工作。这是一个错字。 – anthony

0

您可以使用可选参数更新bar()方法作为设置栏。

公共功能栏($ mycolor ='red') { $ this-> var1 = $ mycolor; return $ this-> var1; }