Can I extend a class after the parent class is created?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kenja
Forum Newbie
Posts: 4
Joined: Mon Apr 21, 2008 11:02 pm

Can I extend a class after the parent class is created?

Post by kenja »

I'm trying to extend a class after the parent class already is defined. Is that possible? If so, how do you do it? The functions that allow me to determine what object type is needed is inside the parent class.

Here's an example:

Code: Select all

public class shape{
  private $shapeData;  //large object filled with data that is used later in other class functions
  private $shapeType;  
  public __construct($urlToShapeData){
    $this->shapeData=getXML($urlToShapeData)  //function does not exist, but illustrates the point.
    $shapeType = determineShapeType($this->shapeData);
  }
  private function determineShapeType(){
    if($this->shapeType=="circle"){
       //extend class to be a circle
    }elseif($this->shapeType=="square"){
       //extend class to be a square
    }
  }
  abstract public function doStuff();
}
 
public class circle extends shape{
  public function doStuff(){
   //Do circle specific stuff
  }
}
 
public class square extends shape{
  public function doStuff(){
  //Do square specific stuff
  }
}
 
$shape=new shape();  //creates the parent, which is then automatically extended into the correct child class
$shape->doStuff();
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Re: Can I extend a class after the parent class is created?

Post by Luke »

I am not sure I follow completely, can you give more information? What are you actually trying to do? No pseudo-code.
User avatar
novice4eva
Forum Contributor
Posts: 327
Joined: Thu Mar 29, 2007 3:48 am
Location: Nepal

Re: ?

Post by novice4eva »

Well you can extend (parent)class after the parent class is created IN a child class but what you are doing in the example in Absolute NO NO, you can't just call doStuff from your parent class since it is abstract!! As for the solution well, you can create a function outside the shape class

Code: Select all

 
public class getShape{
  private $shapeData;  //large object filled with data that is used later in other class functions
  private $shapeType;  
  public __construct($urlToShapeData){
    $this->shapeData=getXML($urlToShapeData)  //function does not exist, but illustrates the point.
    $shapeType = determineShapeType($this->shapeData);
  }
  private function getShapeObj(){
    if($this->shapeType=="circle"){
       return $obj = new circle();
    }elseif($this->shapeType=="square"){
       return $obj = new square();
    }
  }
 
}}
$shapeTyp=new getShape($somePARAM);
$shape = $shapeTyp->getShapeObj();
 
Post Reply