0

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.

5
  • 8
    It does return blue? Commented Mar 16, 2011 at 20:26
  • The above returns "blue" for me on PHP 3.5.3 when I follow it with $t = new TestClass; echo $t->bar();. How are you calling bar()? Since $var1 is non-static, it is an instance property instead of a class property. Commented Mar 16, 2011 at 20:28
  • 1
    I think you mean 5.3.3? Or you got a helluva old version of PHP David =) Commented Mar 16, 2011 at 20:31
  • @Tim Cooper - +1 That site is wicked cool. Commented Mar 16, 2011 at 20:33
  • @PatrikAkerstrand - LOL, yes. Too much time with PHPUnit. ;) Commented Mar 16, 2011 at 20:34

2 Answers 2

3

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?

Sign up to request clarification or add additional context in comments.

2 Comments

same for me, works perfectly fine and I see no reason why it shouldn't
Thanks for the reply. I got it working. It was a typo all along.
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.