O'Reilly logo

Programming PHP, 3rd Edition by Peter MacIntyre, Kevin Tatroe, Rasmus Lerdorf

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:

echo "Rasmus is {$rasmus->age} years old.\n";   // property access
$rasmus->birthday();                            // method call
$rasmus->setAge(21);                            // method call with arguments

Methods act the same as functions (only specifically to the object in question), so they can take arguments and return a value:

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

Within a class’s definition, you can specify which methods and properties are publicly accessible and which are accessible only from within the class itself using the public and private access modifiers. You can use these to provide encapsulation.

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() static method in the HTML class:

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

When declaring a class, you define which properties and methods are static using the static access property.

Once created, objects are passed by reference—that is, instead of copying around the entire object itself (a time- and memory-consuming endeavor), a reference to the object is passed around instead. For example:

$f = new Person("Fred", 35);

$b = $f; // $b and $f ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required