|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2007-06-07 10:14 UTC] amine dot abbes at gmail dot com
Description:
------------
When calling parent::__construct() in the subclass constructor, $this will refere to the subclass instance.
Reproduce code:
---------------
<?php
class MyParent{
function __construct(){
echo (($this instanceof MyClass)?"Yes":"No") . "<br>" ;
self::myfunction();
$this->myfunction();
}
function myfunction(){
echo __METHOD__ . "<br>";
}
}
class MyClass extends MyParent{
function __construct(){
parent::__construct();
}
function myfunction(){
echo __METHOD__ . "<br>";
}
}
new MyClass();
?>
Expected result:
----------------
No
MyParent::myfunction
MyParent::myfunction
Actual result:
--------------
Yes
MyParent::myfunction
MyClass::myfunction
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Oct 27 12:00:02 2025 UTC |
There is an issue because the members (vars) refere to the class englobing "$this" but the functions refere to the caller class. Please check with this code : <?php class MyParent{ private $var = "varMyParent"; function __construct(){ echo "\$this is an instance of MyClass : " . (($this instanceof MyClass)?"Yes":"No") . "<br>" ; echo "Calling \$this->myfunction() in MyParent : "; $this->myfunction(); echo "\$this->var in MyParent = " . $this->var . "<br>"; } function myfunction(){ //echo (($this instanceof MyClass)?"Yes":"No") . " in myfunction MyParent<br>" ; echo __METHOD__ . " - \$this->var = " . $this->var . "<br>"; } } class MyClass extends MyParent{ private $var = "varMyClass"; function __construct(){ parent::__construct(); echo "\$this->var in MyClass = " . $this->var . "<br>"; } function myfunction(){ echo __METHOD__ . " - \$this->var = " . $this->var . "<br>"; } } new MyClass(); ?> Result : $this is an instance of MyClass : Yes Calling $this->myfunction() in MyParent : MyClass::myfunction - $this->var = varMyClass $this->var in MyParent = varMyParent $this->var in MyClass = varMyClass => conclusion : In subclass MyClass inherited from MyParent, $this in parent::__construct() code block has diffrent visibility of variables and functions. The functions will continue to refere to MyClass and the variables will refere to MyParent. This is ambiguous for the developers and should be fixed.