0

I would expect the following code to write "bar", but getFoo returns NULL.

What is the problem with that code, and how can i fix this?

<?php class A { protected $foo; public function getFoo() {return $this->foo;} public function setFoo($foo) {$this->foo = $foo;} } class B extends A{} $a = new A(); $a->setFoo("bar"); $b = new B(); echo $b->getFoo(); 
1
  • OOP concept fails here. The object $a sets the variable $foo='bar' but the object $b hasn't set the variable $foo yet. So it returns null. Whereas $a->getFoo() would return "bar" not null. Commented Mar 7, 2014 at 10:31

2 Answers 2

2

Im not really sure what you are doing, and i am quite sure you should read up on exactly how inheritance and objects work. You are specifying 2 classes witch is a template to build an object from. You the instanciate 2 objects $a and $b but these two objects do not share data.

You could use a static variable to do what you want but im not really sure what you are trying to achieve:

<?php class A { protected static $foo; public function getFoo() {return self::$foo;} public function setFoo($foo) {self::$foo = $foo;} } class B extends A{} $a = new A(); $a->setFoo("bar"); $b = new B(); echo $b->getFoo(); 

Outputs: "bar"

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

1 Comment

Right. I guess i have to change my logic.
0

Your expectation is wrong. $a and $b are different instances. You set $foo in one instance, then create another that does not know about the first one.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.