[]RSS

About Archives Artwork Comic Contact Philosophy Projects Tags

Optional arguments in PHP

July 16th, 2008 in Micro Blog

Named, optional function arguments are a commonly used calling convention in Perl modules, used for constructors and heavily overloaded functions. They’re usually implemented with hashes in Perl, and while somewhat more work to iterate in the library than fixed arguments, they clearly document the call for the caller (and tend to be far less fragile).

They’re also easy to implement in PHP. Here’s an example (based on some CodeIgniter code I had laying around):

class bar extends Controller {

    protected $data = array();

    function foo($name, $extras = array('desc' => 'default1', 'on' => false)) {
        $this->data = array_merge($this->data, $extras);
    }

}
  1. The optional parameters are defined as the array elements of the $extra default array parameter value.
  2. The optional parameters are merged with the class data $this->data.

Calling the function is simple:

$b.foo('test', array('on' => true));
$b.foo('test 2' /* uses defaults */ );
$b.foo('test 3', array('desc' => 'Here is a description'));

The caller’s syntax isn’t quite as clean as Perl’s, but applying the defaults is cleaner (and merging the structures is about equivalent). Despite the slightly more complex calling convention, it’s still useful for setup functions with multiple optional parameters.

 

Leave a Reply

Subscribe to comments