anthony
anthony

Reputation: 902

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 dynamic properties.

Upvotes: 0

Views: 173

Answers (2)

Tariq
Tariq

Reputation: 147

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

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

Upvotes: 0

Charles
Charles

Reputation: 51421

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?

Upvotes: 3

Related Questions