Getting Started with Objects with PHP V5
By Matt Zandstra2005-07-01
Methods
Put simply, methods are functions declared within a class. They are usually -- but not always -- called via an object instance using the object operator. Listing 5 adds a method to the
Dictionary class and invokes it.Listing 5. Adding a method to the Dictionary class |
It provides output of:
|
As you can see, the summarize() method is declared just as any function would be declared, except that is done within a class. The summarize() method is invoked via a Dictionary instance using the object operator. The summarize() function accesses properties to provide a short overview of the state of the object.
Notice the use of a feature new to this article. The $this pseudo-variable provides a mechanism for objects to refer to their own properties and methods. Outside of an object, there is a handle you can use to access its elements ($en, in this case). Inside an object, there is no such handle, so you must fall back on $this. If you find $this confusing, try replacing it in your mind with the current instance when you encounter it in code.
Classes are often represented in diagrams using the Universal Modeling Language (UML). The details of the UML are beyond the scope of this article, but such diagrams are nonetheless an excellent way of visualizing class relationships. Figure 1 shows the Dictionary class as it stands. The class name lives in the top layer, properties in the middle, and methods at the bottom.
Figure 1. The Dictionary class shown using the UML
Tutorial Pages:
» Why you need to know objects and classes, and how to use them
» What are classes and objects?
» A first class
» Properties
» Methods
» The constructor
» Keywords: Can we have a little privacy in here?
» Working in class context
» Inheritance
» Summary
» Resources
First published by IBM DeveloperWorks
