Accessing Properties and Methods PHP

The properties of an instance are variables, just like any other PHP variable. To refer to them, however, you must use the -> operator. You do not use a dollar sign in front of the property name. For an example, refer to the line in Listing 6.1 that prints the name property of the currentUser object.

Use of -> can be chained. If an object's property contains an object itself, you can use two -> operators to get to a property on the inner object. The parser in PHP 3 was unable to deal with complex expressions like this. In PHP 4 you are not limited this way. You may even place these expressions within double-quoted strings.

Unlike object-oriented languages, such as C++, PHP does not allow properties of classes to be private. Any code may reach into the instance and change or read the values of properties.
Accessing methods is similar to accessing properties. The -> operator is used to point to the instance's method. Methods behave exactly as functions defined outside classes.

If a class extends another, the properties and methods of all ancestor classes are available in the child class, despite not being declared explicitly. As mentioned previously, inheritance is very powerful. If you wish to access an inherited property, simply refer to it as you would any other local property.

Three functions allow you to get information about a class as your script runs: get_class, get_parent_class, and method_exists.

Objects Containing Other Objects

Objects Containing Other Objects

Objects Containing Other Objects


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

PHP Topics