13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

150 Chapter 5 Reusing Code <strong>and</strong> Writing Functions<br />

If you want the same data displayed in a more spread-out style, you could call the new<br />

function as follows:<br />

create_table2($my_array, 3, 8, 8);<br />

Optional values do not all need to be provided; you can provide some <strong>and</strong> ignore some.<br />

Parameters are assigned from left to right.<br />

Keep in mind that you cannot leave out one optional parameter but include a later<br />

listed one. In this example, if you want to pass a value for cellspacing, you will have to<br />

pass one for cellpadding as well.This is a common cause of programming errors. It is<br />

also the reason that optional parameters are specified last in any list of parameters.<br />

The function call<br />

create_table2($my_array, 3);<br />

is perfectly legal <strong>and</strong> results in $border being set to 3 <strong>and</strong> $cellpadding <strong>and</strong><br />

$cellspacing being set to their defaults.<br />

You also can declare functions that accept a variable number of parameters.You can<br />

find out how many parameters have been passed <strong>and</strong> what their values are with the aid<br />

of three helper functions: func_num_args(), func_get_arg(), <strong>and</strong> func_get_args().<br />

For example, consider this function:<br />

function var_args() {<br />

echo "Number of parameters:";<br />

echo func_num_args();<br />

echo "";<br />

$args = func_get_args();<br />

foreach ($args as $arg) {<br />

echo $arg."";<br />

}<br />

}<br />

This function reports the number of parameters passed to it <strong>and</strong> prints out each of them.<br />

The func_num_args() function returns the number of arguments passed in.The<br />

func_get_args() function returns an array of the arguments. Alternatively, you can<br />

access the arguments one at a time using the func_get_arg() function, passing it the<br />

argument number you want to access. (Arguments are numbered starting from zero.)<br />

Underst<strong>and</strong>ing Scope<br />

You might have noticed that when we needed to use variables inside a required or<br />

included file, we simply declared them in the script before the require() or include()<br />

statement.When using a function, we explicitly passed those variables into the function<br />

partly because no mechanism exists for explicitly passing variables to a required or<br />

included file <strong>and</strong> partly because variable scope behaves differently for functions.

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

Saved successfully!

Ooh no, something went wrong!