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 ...

Get Programming PHP, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.