13.09.2016 Views

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

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

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

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

have the same name as any built-in function or an existing user-defined function. Note<br />

that although every <strong>PHP</strong> script knows about all the built-in functions, user-defined<br />

functions exist only in scripts where they are declared.This means that you could<br />

reuse a function name in a different file, but this would lead to confusion <strong>and</strong> should<br />

be avoided.<br />

The following function names are legal:<br />

name()<br />

name2()<br />

name_three()<br />

_namefour()<br />

These names are illegal:<br />

5name()<br />

name-six()<br />

fopen()<br />

(The last would be legal if it didn’t already exist.)<br />

Note that although $name is not a valid name for a function, a function call like<br />

$name();<br />

may well execute, depending on the value of $name.The reason is that <strong>PHP</strong> takes the<br />

value stored in $name, looks for a function with that name, <strong>and</strong> tries to call it for you.<br />

This type of function is referred to as a variable function <strong>and</strong> may occasionally be useful<br />

to you.<br />

Using Parameters<br />

To do their work, most functions require one or more parameters. A parameter allows<br />

you to pass data into a function. Here is a sample function that requires a parameter; it<br />

takes a one-dimensional array <strong>and</strong> displays it as a table:<br />

function create_table($data) {<br />

echo "";<br />

reset($data); // Remember this is used to point to the beginning<br />

$value = current($data);<br />

while ($value) {<br />

echo "".$value."\n";<br />

$value = next($data);<br />

}<br />

echo "";<br />

}<br />

If you call the create_table() function as follows<br />

$my_array = array(‘Line one.’,’Line two.’,’Line three.’);<br />

create_table($my_array);<br />

you will see output as shown in Figure 5.4.

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

Saved successfully!

Ooh no, something went wrong!