Tag Archives: php 5.3

Functional programming in PHP

With the introduction of lambda (or anonymous) functions in PHP 5.3 it is now possible to introduce some nice features from the functional programming paradigm.

Higher order function

When a method (or function) accepts another function as parameter this function is called a higher order function. The following already worked in PHP < 5.3 and is a simple implementation of functional programming with callable variables.

$data = array(10,2,6,4);
function cmp($a, $b) {
    if ($a == $b) return 0;
    return $a < $b ? -1 : 1;
}
usort($data, "cmp");

Continue reading Functional programming in PHP

Singleton pattern in PHP 5.3

With the introduction of PHP 5.3 some nice object oriented features are available. One of them is the function get_called_class. Below a short example when this function comes in handy.

When we have an abstract CacheDriver as shown below and we extend this with a MemcachedDriver. We only want one instance of this driver available so we apply the singleton pattern. But before PHP 5.3 it was very difficult to put the getInstance method in the base class. There is a solution to use the factory pattern (eg. CacheDriver::getInstance('Memcached')) but the following solution is more elegant and possible from PHP 5.3

Because get_called_class() yields the name of the class we are using (MemcachedDriver) we get directly an instance of the MemcachedDriver without duplicating the getInstance method or using the factory pattern.