note 94177 added to keyword.parent

From: Date: Wed, 21 Oct 2009 05:32:07 +0000
Subject: note 94177 added to keyword.parent
Groups: php.notes 
Request: Send a blank email to php-notes+get-161931@lists.php.net to get a copy of this message
I've seen people in the comments below use this, but I've also seen some unecessary workarounds to achieve it. So I thought I'd clarify, even though it is shown in the documentation. You CAN reference non-static parent methods, as in other languages. For example... <?php abstract class ParentClass { public function doSomething() { echo "done.\n"; } } class ChildClass extends ParentClass { public function doSomething() { echo "attempting something.\n"; parent::doSomething(); } } $obj = new ChildClass(); $obj->doSomething(); ?> This will output both "attempting something." and "done." As you might expect, it also works if the parent method is protected. Users of other languages may have tried defining static and non-static methods with the same name. This is why that doesn't work ("parent" can refer to both static and non-static methods, and there's no way to differentiate them). However, you CANNOT use the "parent" keyword to reference the parent's variables. When in a class, "parent" will always look for static variables. For example, this results in an "Access to undeclared static property" fatal error: <?php abstract class ParentClass { public $var = 5; } class ChildClass extends ParentClass { public function setVar($val) { parent::$var = $val; } public function getVar() { return parent::$var; } } $obj = new ChildClass(); $obj->setVar(6); // Results in fatal error. echo $obj->getVar() . "\n"; // Results in fatal error. echo $obj->var . "\n"; // Would work and reference the parent's $var unless the child has its own $var. ?> ---- Server IP: 69.147.83.197 Probable Submitter: 70.47.131.176 ---- Manual Page -- http://www.php.net/manual/en/keyword.parent.php Edit -- https://master.php.net/note/edit/94177 Del: integrated -- https://master.php.net/note/delete/94177/integrated Del: useless -- https://master.php.net/note/delete/94177/useless Del: bad code -- https://master.php.net/note/delete/94177/bad+code Del: spam -- https://master.php.net/note/delete/94177/spam Del: non-english -- https://master.php.net/note/delete/94177/non-english Del: in docs -- https://master.php.net/note/delete/94177/in+docs Del: other reasons-- https://master.php.net/note/delete/94177 Reject -- https://master.php.net/note/reject/94177 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#161931) next »