9.6 Returning a Different Object from a Constructor


You want to return a new object from an object's constructor, but return won't allow you to do this (at least not in a constructor).

Technique

Assign the new object to the $this variable:

 <?php class PHP_QA {     var $name;     function std_response () {         print "Sorry " . $this->name;         print ", That's a feature not a bug\n";     } } class BUG {     var $type;     function BUG ($type) {         if ($type == "Invalid Bug") {             $this = &new PHP_QA;             return;         }         $this->type = $type;     }     function std_response () {         print "Wow, thanks for reporting a " . $this->type;         print " error!!";     } } ?> 

Comments

If you want to return a different object from a constructor, you must assign the $this variable the new object. The $this variable is the default return value from a constructor; it contains a pointer to the methods and properties of the current class. Overriding the $this variable enables you to change the object returned from the constructor. Note, however, that you lose all the current class's methods and properties when you assign a new value to the $this variable.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net