25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

42 ” Functions<br />

Variable-length Argument Lists<br />

A common mistake when declaring a function is to write the following:<br />

function f ($optional = "null", $required)<br />

{<br />

}<br />

This does not cause any errors to be emitted, but it also makes no sense whatsoever—because<br />

you will never be able to omit the first parameter ($optional) if you<br />

want to specify the second, and you can’t omit the second because <strong>PHP</strong> will emit a<br />

warning.<br />

In this case, what you really want is variable-length argument lists—that is, the<br />

ability to create a function that accepts a variable number of arguments, depending<br />

on the circumstance. A typical example of this behaviour is exhibited by the printf()<br />

family of functions.<br />

<strong>PHP</strong> provides three built-in functions to handle variable-length argument lists:<br />

func_num_args(), func_get_arg() and func_get_args(). Here’s an example of how<br />

they’re used:<br />

function hello()<br />

{<br />

if (func_num_args() > 0) {<br />

$arg = func_get_arg(0); // The first argument is at position 0<br />

echo "Hello $arg";<br />

} else {<br />

echo "Hello World";<br />

}<br />

}<br />

hello("Reader"); // Displays "Hello Reader"<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

hello(); // Displays "Hello World"<br />

You can use variable-length argument lists even if you do specify arguments in the<br />

function header. However, this won’t affect the way the variable-length argument list<br />

functions behave—for example, func_num_args() will still return the total number of<br />

arguments passed to your function, both declared and anonymous.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!