9.9 Indirectly Accessing a Method of the Parent Class


You want to access a method of a parent class without explicitly naming the class you want to access.

Technique

Use the special parent class to access the method of a parent class:

 <?php class Computer {     var $is_on = 1;     function turn_on () {         $this->is_on = 1;         print "You turned me on";     }     function turn_off () {         $this->is_on = 0;         print "You turned me off";     } } class HP extends Computer {     var $processor = 0;     var $hard_drive = 0;     function turn_on() {         parent::turn_on();         $this->processor = 1;         $this->hard_drive = 1;     }     function turn_off() {         $this->hard_drive = 0;         $this->processor = 1;         parent::turn_off();     } } ?> 

Comments

The parent class is a special class that can be accessed only by using the :: notation. It enables you to access methods from the parent class of the current class. This is useful in the example because the turn_on() and turn_off() methods are defined in both the parent ( Computer ) and the child ( HP ) class. Therefore, if we accessed turn_on() or turn_off() through $this , we would get the current turn_on() and turn_off() methods, not the methods in the parent class.

If you don't have a namespace collision between the two classes, you can directly access parent methods by using the $this object. Accessing parent methods via the $this object preserves the current object's properties. Consider the following example, which works only when you use the $this object:

 <?php class Parent {     var $parent_name;     function print_parent_name () {         print $this->parent_name . "\n";     } } class Child extends Parent {     var $child_name;     function print_child_name () {         print $this->child_name . "\n";     } } $obj = &new Child; $obj->child_name = "Sterling"; $obj->parent_name = "Leslie"; print "Parent name: "; $this->print parent_name(); print "Child name: "; $this->print_child_name(); ?> 


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