note 87270 deleted from language.oop5.basic by cmb

From: Date: Mon, 21 Nov 2016 18:21:14 +0000
Subject: note 87270 deleted from language.oop5.basic by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-207273@lists.php.net to get a copy of this message
Note Submitter: chris (@) xeneco (dot) co (dot) uk ---- Regarding object inheritance: I hope this helps someone, it should help if you're new to OOPS <?php class A { public $x = 'A'; public function foo() { $b = new B; $b->bar(); return $this->x; } } class B extends A { public function bar() { $this->x = 'B'; } } $a = new A echo $a->foo(); //A ?> I was doing something similar to this (example is greatly simplified to show logic) and spent a long while trying to work out why I would always get 'A' and never get 'B'. Now, after a few weeks, I have revisited the problem and have worked out why: The code 'new B' creates a new instance of class B. While class B extends class A, it is a new object and not an extension of the object created by 'new A' The value of $x is set to 'B' within the object $b, but not in object $a. If within A::foo(), one was to access $b->x then one would obtain the vale 'B', for example <?php class C { public $x = 'C'; public function foo() { $c = new C; $c->bar(); $this->x = $c->$x return $this->x; } } class D extends C { public function bar() { $this->x = 'D'; } } $c = new C echo $c->foo(); //D ?>

« previous php.notes (#207273) next »