Jim Lucas wrote:
> 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.
>>
> 
> To use Richards example, but with a little different twist for accessing
> the parent methods/properties
> 
> class A
> {
>     public __construct()
>     {
>         // ...
>     }
>     public function foo ()
>     {
>         // ...
>     }
> }
> 
> class B extends A {
>     // Constructor
>     public function __construct ()
>     {
>         parent::__construct();
>     }
> }
> 
> 
> // And then...
> 
> $b = new B();
> $b->foo();
> 
> 
> This will bring all methods/properties from class A into class B.

both methods & properties of the parent (class A) are available assuming they
are public or protected - if you don't call the parent ctor the only
thing your missing is whatever initialization of data and/or property values 
(etc)
would have been done by the parent ctor.

class A {
        public function foo() {echo "achoo";}
}
class B extends A {}

$b = new B;
$b->foo();

it is quite normal to call parent::__construct(); in the subclass' ctor but it's
not required to make methods/properties available and I don't see what baring
it has on the OP's question.

another solution for the OP might be (although I think it goes against all
design principles):

class A {
  function foo() {
    echo "achoo\n";
  }
}

class B extends A {
  function foo() {
    echo "cough\n";
  }
  function __call($meth, $args) {
    $func = array(parent, strtolower(str_replace("parent","", $meth)));
    if (is_callable($func))
      return call_user_func_array($func, $args);
  }
}

$b = new B;
$b->foo();
$b->parentFoo();

> 
> You can choose to override class A methods/properties when you define
> class B.
> But the idea here is that only need to write the methods/properties once
> in the parent class,
> then you can extend your class with class A and have all the
> methods/properties available to you
> within your current class.
> 
> It is good to practice the DRY principle here.
> 
> 
> 
> Note: Richard Heyes thanks for the code snippet
> 
> 
> 

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

Reply via email to