note 69850 deleted from ref.classobj by bjori

From: Date: Sat, 23 Sep 2006 10:00:40 +0000
Subject: note 69850 deleted from ref.classobj by bjori
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-117465@lists.php.net to get a copy of this message
Note Submitter: frankdrakkman at yahoo dot com Reason: funny code ---- <? //PHP5.X /* Dynamically load objects Here is how you can inherit all methods from any of your Classes without having to use extended. Therefore, you can create multiple inheritance in PHP sort of like C++. */ // If the Generic Classes were located in different // files and if you name your files after your classes // i.e. Class1.php - Class2.php - Class3.php // use the autoload function if(!function_exists("__autoload")){ function __autoload($classname) { require_once $classname . '.php'; } } //Take a look at Class3 ////////////// Begin Generic Classes ///////////////////// class Class1 { public function doSomething(){ echo "<br />doSomething() in ".get_class($this); } public function doSomethingElse(){ echo "<br />doSomethingElse() in ".get_class($this); } } // end class Class1 class Class2 { public function doSomethingDiff(){ echo "<br />doSomethingDiff() in ".get_class($this); } } // end class Class2 class Class3 { public function doThisThing(Class1 $obj){ echo get_class($this); echo " calling... "; echo $obj->doSomething(); // call Class1 method } } // end class Class3 //////////////// End Generic Classes //////////////////// //////////////// Begin MultiInherit Class /////////////// /* The class MultiInherit is the key to this working. This could be more dynamic if you prefer, but keep in mind that runtime errors are less likely using single inheritance. */ class MultiInherit { public $obj = array();//create class variable type array public function setObj(array $obj){ // type hinting $this->obj = $obj; } // end function setObj() } // end class MultiInherit //////////////// End MultiInherit Class ///////////////// $objs = array(); $objs[1] = new Class1(); // create instance of Class1 $objs[2] = new Class2(); // create instance of Class2 $objs[3] = new Class3(); // create instance of Class2 $mi = new MultiInherit(); // create instance of MultiInherit $mi->setObj($objs); // send array obj to setObj function // Notice instance of class MultiInherit calls all of the // other class' methods. echo $mi->obj[1]->doSomething(); echo $mi->obj[1]->doSomethingElse(); echo $mi->obj[2]->doSomethingDiff(); echo "<br /><br />"; echo $mi->obj[3]->doThisThing($objs[1]); /* EXPECTED OUTPUT: doSomething() in Class1 doSomethingElse() in Class1 doSomethingDiff() in Class2 Class3 calling... doSomething() in Class1 */ ?>

« previous php.notes (#117465) next »