Page 213 - Beginning PHP 5.3
P. 213
Chapter 8: Objects
Calling Methods
To call an object ’ s method, simply write the object ’ s name, then the same arrow used for accessing
properties ( - > ), then the method name followed by parentheses:
$object-> method();
Here ’ s a simple example that creates a class with a method, then creates an object from the class and calls
the object ’ s method:
class MyClass {
public function hello() {
echo “Hello, World!”;
}
}
$obj = new MyClass;
$obj-> hello(); // Displays “Hello, World!”
Adding Parameters and Returning Values
As with functions, which you studied in the previous chapter, you can add parameters to a method so
that it can accept arguments to work with. A method can also return a value, just like a function.
You add parameters and return values in much the same way as with functions. To add parameters,
specify the parameter names between the parentheses after the method ’ s name:
public function aMethod( $param1, $param2 ) {
// (do stuff here)
}
To return a value from a method — or to simply exit a method immediately — use the return keyword:
public function aMethod( $param1, $param2 ) {
// (do stuff here)
return true;
}
Accessing Object Properties from Methods
Although you can happily pass values to and from a method using parameters and return values,
much of the power of OOP is realized when objects are as self - contained as possible. This means that
an object ’ s methods should ideally work mainly with the properties of the object, rather than relying on
outside data to do their job.
175
9/21/09 9:03:33 AM
c08.indd 175
c08.indd 175 9/21/09 9:03:33 AM