"
";
echo $employee->age;
This returns the following:
Mario
__get called!
No such variable!
Creating Custom Getters and Setters
Frankly, although there are some benefits to the __set() and __get() methods, they
really aren??™t sufficient for managing properties in a complex object-oriented application.
Because PHP doesn??™t offer support for the creation of properties in the fashion
that Java or C# does, you need to implement your own methodology. Consider creating
two methods for each private field, like so:
176 CHAPTER 6 ?– O BJECT-ORIENTED PHP
class Employee
{
private $name;
// Getter
public function getName() {
return $this->name;
}
// Setter
public function setName($name) {
$this->name = $name;
}
}
?>
Although such a strategy doesn??™t offer the same convenience as using properties, it
does encapsulate management and retrieval tasks using a standardized naming convention.
Of course, you should add additional validation functionality to the setter; however,
this simple example should suffice to drive the point home.
Constants
You can define constants, or values that are not intended to change, within a class.
These values will remain unchanged throughout the lifetime of any object instantiated
from that class. Class constants are created like so:
const NAME = 'VALUE';
For example, suppose you create a math-related class that contains a number of
methods defining mathematical functions, in addition to numerous constants:
class math_functions
{
const PI = '3.
Pages:
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256