开发者

PHP Class Variables Reassignment

Is it possible to make the following bar() method return "blue"?

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;
        }
}

I know that class properties can't be variables, results of addition, etc. I read about overloading using __set and __get, however that seems to be geared towards totally d开发者_StackOverflow社区ynamic properties.


Your code currently works as you describe it. From the PHP interactive shell:

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

Perhaps you can explain your problem in a different way?


You can update bar() method as set bar with optional parameter.

public function bar($mycolor='red') { $this->var1 = $mycolor; return $this->var1; }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜