9.2 Accessing Variables from Within a Class


9.2 Accessing Variables from Within a Class

You want to access variables declared via the var statement, but you can't call them by name from within the class.

Technique

Use the built-in $this object to access variables in the class:

 <?php class Name {     var $firstname;     var $lastname;     function print_names() {         print 'Firstname: ' .  $this->firstname;         print "\nLastname: " . $this->lastname;     } } ?> 

Comments

$this is a special variable that is created in an object. It refers to the object itself, meaning that through $this you can access class variables and methods in the current class. The $this object represents the same idea as manually creating an instance of the class within the class. Therefore, we can also change the values of the object's properties:

 <?php class Name {     var $firstname;     var $lastname;     function print_names() {         print 'Firstname: ' . $this->firstname;         print "\nLastname: ' . $this->lastname;     }     function change_name ($name) {         $name = preg_split('/\s+/', $name);         $this->firstname = $name[0];         $this->lastname  = $name[1];     } } $obj = &new Name; $obj->change_name("Sterling Hughes"); $obj->print_name(); $obj->change_name("Andrei Zmievski"); $obj->print_name(); ?> 

The change_name() method will change the name of the person who is described in the Name object, and the print_name() method will reflect the change.



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