Re: calling parent class method from the outside

From: Date: Mon, 02 Jul 2007 14:49:08 +0000
Subject: Re: calling parent class method from the outside
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-258040@lists.php.net to get a copy of this message
admin wrote: > Inside the body of method foo() you can of course use syntax like > parent::foo(). But is there a way to call the parent version of > obj->foo() outside the class? That kind of syntax is allowed in C++, for > example: Aclass a; if (a.Aparent::foo()) ...; > > Some contrived example to illustrate the point: > > class AParent { > public function foo() { .. } > } > > class A extends AParent { > public function foo() { > doit($this, __CLASS__, __FUNCTION__); > } > } > > function doit($obj, $classname, $funcname) { > if (...) > // $obj->classname_parent::$funcname(); > } > > > Thanks. I agree with Jochem that if you find you need to do this, then you're probably not designing the code correctly. There are a few options in my mind that you can potentially use depending on what you're actually doing: 1. Don't overload the function in A at all. Then you call $obj->foo(), it will be the parent method that is called. 2. If you have a large chunk of code in the parent and you don't want to reimplement it in the child as it's only slightly different, break up the functionality into a Protected method: Class AParent { protected function foo_() { .... } public function foo() { return $this->foo_() } } class A extends AParent { public function foo() { $something = 'a bit different'; return $this->foo_(); } 3. Sometimes a neater version of the above can be used if you only ever extend something: Class AParent { public function foo() { .... } } class A extends AParent { public function foo() { $something = 'a bit different'; return parent::foo(); } HTHs Col

« previous php.general (#258040) next »