9.5 Creating a Constructor


You want to create a function that is called when an instance of a class is created via the new statement; this is known as a constructor.

Technique

Give your constructor function the same name as the class you are calling:

 <?php class Human {     var $name;     function Human ($na) {         print "Wake up $na, you have been initialized";         $this->name = $na;     } } $obj = &new Human('Stephen Hughes'); ?> 

Comments

In PHP, a constructor is defined as a method that has the same name (case-sensitive) as the class. The constructor can take arguments, which allows for customization of the object at the initialization time. Also note that if a parent class also has a constructor, the parent class's constructor will not be called when a child class is instantiated . So, you have to do a bit of a manual work. Suppose that you have the following child class to the class Human specified earlier:

 <?php class SuperHuman extends Human {     var $power;     function SuperHuman($power) {        Human::Human();        $this->$power = $power;     }     function use_power() {     /* this should do something interesting */     } } ?> 

Here the SuperHuman constructor will be called, but the Human constructor will not automatically be called. So, you have to call it manually using :: notation (see recipe 9.6).



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