Basics of 'functions as first class language objects'
Yep. PHP can assign functions to variables. In this sense functions are first class objects. Object and class methods are similar, you can, kind of, assign them to variables and later execute them. What does this change? Well, it improves our ability to abstract common patterns and idioms. There are examples of this in the above writeups as well as in the aspects one and quite a few of the rest of php ones on this site. The basic concept is php callback for example:
call_user_func('a_callback_function');
call_user_func(array('AClass', 'aCallback'));
call_user_func(array($obj, 'aCallback'));
$callback = 'a_callback_function';
$callback();
$callback = array($obj, 'aCallback');
$callback();
What can we use this for? The most obvious and straight forward this is a lightweight state pattern implementation -
$a_thing()
Will behave differently depending on the value of the $a_thing variable, it's state. Another way to look at php callbacks is as proxies for 'real' functions, class or object methods.
Oh, let's not forget is_callable, it's a very useful little number.
Objects and functions
The facility of PHP objects to encapsulate a state and us being able to access this state later can be used to turn them into functions. Let's consider:
class aClass{
var $state;
function get() { return $state; }
function next() { $state=random; }
function callbacks() { return array( array($this,'get'), array($this, 'next'));}
}
$obj = new aClass();
list( $random, $next_random ) = $obj->callbacks();
echo $random();
echo $next_random();