Page 1 of 1

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

Posted: Tue Dec 09, 2008 7:38 pm
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();

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

Posted: Tue Dec 09, 2008 7:56 pm
by Luke
I am not sure I follow completely, can you give more information? What are you actually trying to do? No pseudo-code.

Re: ?

Posted: Tue Dec 09, 2008 8:04 pm
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();