home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Programming PHPProgramming PHPSearch this book

6.3. Accessing Properties and Methods

Once you have an object, you can use the -> notation to access methods and properties of the object:

$object->propertyname
$object->methodname([arg, ... ])

For example:

printf("Rasmus is %d years old.\n", $rasmus->age);  // property access
$rasmus->birthday();                                // method call
$rasmus->set_age(21);                               // method call with arguments

Methods are functions, so they can take arguments and return a value:

$clan = $rasmus->family('extended');

PHP does not have the concept of private and public methods or properties. That is, there's no way to specify that only the code in the class should be able to directly access a particular property or method. Encapsulation is achieved by convention—only an object's code should directly access its properties—rather than being enforced by the language itself.

You can use variable variables with property names:

$prop = 'age';
echo $rasmus->$prop;

A static method is one that is called on a class, not on an object. Such methods cannot access properties. The name of a static method is the class name, followed by two colons and the function name. For instance, this calls the p( ) method in the HTML class:

HTML::p("Hello, world");

A class's documentation tells you which methods are static.

Assignment creates a copy of an object with identical properties. Changing the copy does not change the original:

$f = new Person('Fred', 35);
$b = $f;                               // make a copy
$b->set_name('Barney');                // change the copy
printf("%s and %s are best friends.\n", $b->get_name(), $f->get_name( ));
Barney and Fred are best friends.


Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.