Re: Calling static child method from inherited static parent method

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

 



===ORIGINAL===
I'm trying to implement what I think is called a "virtual method": my
abstract parent class ParentClass defines a method xxx that calls
method yyy, but yyy is defined only in ParentClass's children.

I can't get this to work (PHP5.0.4). Sample code:

=== start sample code ===

abstract class ParentClass {
 // xxx just returns 5 + whatever yyy() returns
 public static function xxx () {return 5 + yyy();}
 // all my children must define yyy()
 abstract static function yyy();
}

abstract class ChildClass extends ParentClass {
 public static function yyy () {return 7;}
}

echo ChildClass::xxx();

=== end sample code ===

When I run the above, I get this error:

Fatal error: Call to undefined function yyy() in <file> on line 9

Changing the call from yyy() to self::yyy() gives a different error:

Fatal error: Cannot call abstract method ParentClass::yyy() in <file> on
line 9

How to do this correctly?
===END ORIGINAL===

The following code works..Reasons:
1. both of your classes are abstract
2. In Parent class you cannot referr to yyy() or self::yyy() cause 'self'
points to the same class and calling yyy() searches for a global yyy()
function.

abstract class ParentClass {
 // xxx just returns 5 + whatever yyy() returns
 public function xxx () {
 return 5 + $this->yyy();
 }
 // all my children must define yyy()
 abstract function yyy();
}

class ChildClass extends ParentClass {
 public function yyy ()
 {
   return 7;
}
}


$obj=new ChildClass;
echo $obj->xxx();
--
Regards
Fahad Pervaiz
www.ecommerce-xperts.com
(Shopping Cart, Web Design, SEO)

[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