9.2 Accessing Variables from Within a Class
TechniqueUse 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. |