Re: calling parent class method from the outside

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux