note 52962 deleted from language.oop.constructor by danbrown
| From: | danbrown@php.net | Date: | Sat, 07 Nov 2009 18:57:16 +0000 |
| Subject: | note 52962 deleted from language.oop.constructor by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-162525@lists.php.net to get a copy of this message | ||
Note Submitter: jfonseca at matarese dot com
----
This will save you time if you're building a class hierarchy with 2 or more levels of
inheritance.
$this always refers to the CURRENT INSTANCE. Therefore if you have:
class A{
function A(){
}
// ....
}
class B extends A{
function B(){
// keep these 2 lines in mind
$parentClass = get_parent_class($this);
$this->$parentClass();
}
// ....
}
class C extends B{
function C(){
$parentClass = get_parent_class($this);
$this->$parentClass();
// here you will get into an infinite loop calling B();
}
// ....
}
Explanation: $this is an instance variable referring to the CURRENT INSTANCE, therefore the $this
variable on class B will always be an instance of C, therefore get_parent_class($this) in class B
will call the constructor of C's parent class, which is B again.
This is a hard to track error if you're a novice on PHP's OO features mainly because PHP
will not produce any warnings, errors or notices, nor will it log anything to Apache or the
error_log file.
Keywords : infinite recursion, parent constructor, subclass