Prev | Current Page 246 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

Note, however, that a method
isn??™t confined to working solely with class fields; it??™s perfectly valid to pass in arguments
in the same way you can with a function.
178 CHAPTER 6 ?–  O BJECT-ORIENTED PHP
?– Tip In the case of public methods, you can forgo explicitly declaring the scope and just declare the
method like you would a function (without any scope).
Invoking Methods
Methods are invoked in almost exactly the same fashion as functions. Continuing
with the previous example, the calculateSalary() method would be invoked like so:
$employee = new Employee("Janie");
$salary = $employee->calculateSalary();
Method Scopes
PHP supports six method scopes: public, private, protected, abstract, final, and static.
The first five scopes are introduced in this section. The sixth, static, is introduced in
the later section ???Static Class Members.???
Public
Public methods can be accessed from anywhere at any time. You declare a public
method by prefacing it with the keyword public or by forgoing any prefacing whatsoever.
The following example demonstrates both declaration practices, in addition to
demonstrating how public methods can be called from outside the class:
class Visitors
{
public function greetVisitor()
{
echo "Hello
";
}
function sayGoodbye()
{
echo "Goodbye
";
}
}
CHAPTER 6 ?–  O BJECT-ORIENTED PHP 179
Visitors::greetVisitor();
$visitor = new Visitors();
$visitor->sayGoodbye();
?>
The following is the result:
Hello
Goodbye
Private
Methods marked as private are available for use only within the originating class and
cannot be called by the instantiated object, nor by any of the originating class??™s
subclasses.


Pages:
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258