Posted on Wednesday, 13th August 2008 by Lee
Overloading PHP So That empty() Works
PHP5 has a much improved object oriented feature set. With great MVC PHP frameworks such as CodeIgniter, CakePHP, and the Zend Framework you should certainly be writing your own classes and taking advantage of objects in your coding. Using the magic methods that you get with PHP5 you can overload your classes so that you can do some very cool stuff.
PHP’s overloading deviates from the way other programming languages work. Overloading in most other languages enables you to define several different methods all with the same name but taking different types of paramters. PHP, on the other hand, uses overloading to handle calls to object members or methods that have not been defined or are not visible in the current scope of the caller.
A Quick Example Of Overloading
Suppose you define a private assoc array to store the data used by your class. Instead of defining bunches of accessor functions, you can take advantage of the __get() and __set() magic methods.
-
<?php
-
class Person {
-
-
public function __set($key, $value) {
-
$this->_data[$key] = $value;
-
}
-
-
public function __get($key) {
-
$value = false;
-
$value = $this->_data[$key];
-
}
-
return $value;
-
}
-
}
-
?>
With this class you can use code like this to set and retrieve values from the private $_data array.
-
<?php
-
class Person {
-
-
public function __set($key, $value) {
-
$this->_data[$key] = $value;
-
}
-
-
public function __get($key) {
-
$value = false;
-
$value = $this->_data[$key];
-
}
-
return $value;
-
}
-
}
-
?>
The Gotcha!
Suppose you want to know if your new Person object has a value for name. You might write code like this.
So what’s up with that? We just defined the worker’s name? The deal is you have to implement the magic __isset() method. The __isset() method is triggered whenever you call non-magic isset() method or the empty() method. So to get everything working as you would expect it to, be sure to define your own magic __isset() method like this.
-
public function __isset($key) {
-
}
The complete class definition will look like this.
-
<?php
-
class Person {
-
-
public function __set($key, $value) {
-
$this->_data[$key] = $value;
-
}
-
-
public function __get($key) {
-
$value = false;
-
$value = $this->_data[$key];
-
}
-
return $value;
-
}
-
-
public function __isset($key) {
-
}
-
}
-
?>
Now when you run this code, you get the answer you would expect.
Now you know... and knowing is half the battle.
Posted in PHP, Web Development | Comments (1)











August 14th, 2008 at 1:33 pm
I found that using magic methods also helps with creating a quasi-factory method for your classes.
Here is a simplified example of a database class that uses drivers.
Class: Database
Class: Database_Driver
Class: Database_Driver_MySQL