note 87270 added to language.oop5.basic
| From: | dot) | Date: | Thu, 27 Nov 2008 11:25:40 +0000 |
| Subject: | note 87270 added to language.oop5.basic | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-147024@lists.php.net to get a copy of this message | ||
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
?>
----
Server IP: 69.147.83.197
Probable Submitter: 194.70.153.162
----
Manual Page -- http://www.php.net/manual/en/language.oop5.basic.php
Edit -- https://master.php.net/note/edit/87270
Del: integrated -- https://master.php.net/note/delete/87270/integrated
Del: useless -- https://master.php.net/note/delete/87270/useless
Del: bad code -- https://master.php.net/note/delete/87270/bad+code
Del: spam -- https://master.php.net/note/delete/87270/spam
Del: non-english -- https://master.php.net/note/delete/87270/non-english
Del: in docs -- https://master.php.net/note/delete/87270/in+docs
Del: other reasons-- https://master.php.net/note/delete/87270
Reject -- https://master.php.net/note/reject/87270
Search -- https://master.php.net/manage/user-notes.php