Re: instantiate derived class objects from within base class?

From: Date: Tue, 02 May 2006 05:14:44 +0000
Subject: Re: instantiate derived class objects from within base class?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-235228@lists.php.net to get a copy of this message
D. Dante Lorenso wrote:
All, I get a fatal error when trying to create a new instance of a derived class from within a static member which exists in the parent base class. I think the problem is related to using this call: new self(); Because the 'self' refers to the parent object and not the derived class. See the code below and the error message which follows: ---------- 8< -------------------- 8< -------------------- 8< ---------- <?php // defines base functions and requires derived class to replace foo() class A { protected abstract function foo(); public static function bar() {
       $x = new self();
       $x->foo();
} } // defines foo() as it should, but base class doesn't know foo exists // when it references self() class B extends A { protected function foo() {
       echo "hello world";
} } // show how broken things are B :: bar(); ?> ---------- 8< -------------------- 8< -------------------- 8< ---------- PHP Fatal error: Class A contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (A::foo) in .../demo.php on line 9
This gives the problem away.. http://www.php.net/manual/en/language.oop5.abstract.php Any class that contains at least one abstract method must also be abstract. Make 'A' abstract: abstract class A -- Postgresql & php tutorials http://www.designmagick.com/

« previous php.general (#235228) next »