Getting Started with Objects with PHP V5
By Matt Zandstra2005-07-01
Properties
Within the body of a class, you can declare special variables called properties. In PHP V4, properties had to be declared with the keyword
var. This is still legal syntax, but mainly for the sake of backward compatibility. In PHP V5, properties should be declared public, private, or protected. You can read about these qualifiers in Keywords: Can we have a little privacy in here? But for now, declare all properties public in the examples. Listing 1 shows a class that declares two properties.Listing 1. A class that declares two properties |
As you can see, you can declare a property and assign its value at the same time. You can get a quick peek at the state of an object with the print_r() function. Listing 2 shows that a Dictionary object now has more to it.
Dictionary object |
You can access public object properties using the object operator '->'. So $en->type means the $type property of the Dictionary object referenced by $en. If you can access a property, it means that you can set and get its value. The code in Listing 3 creates two instances of the Dictionary class -- in other words, it instantiates two Dictionary objects. It changes the $type property of one object and adds translations to both:
Dictionary class |
The script outputs the following:
|
So the Dictionary class is now a little more useful. Individual objects can store distinct sets of keys and values, as well as a flag that tells a client more about the kind of Dictionary this is.
Even though the Dictionary class is currently little more than a wrapper around an associative array, there is some clue to the power of objects here. At this stage, we could represent our sample data pretty well, as shown in Listing 4.
|
Although this data structure fulfills the same purpose as the Dictionary class, it provides no guarantee of the structure. If you are passed a Dictionary object, you know it is designed to have a $translations property. Given an associative array, you have no such guarantee. This fact makes a query like $fr['translations']['TREE']; somewhat hit and miss, unless the code making the query is sure of the provenance of the array. This is a key point about objects: The type of an object is a guarantee of its characteristics.
Although there are benefits to storing data with objects, you are missing an entire dimension. Objects can be things, but crucially they can also do things.
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
