05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Chapter 3 CHAPTER 3<br />

Functions<br />

A function is a named block of code that performs a specific task, possibly acting<br />

upon a set of values given to it, or parameters, and possibly returning a single value.<br />

Functions save on compile time—no matter how many times you call them, functions<br />

are compiled only once for the page. They also improve reliability by allowing<br />

you to fixany bugs in one place, rather than everywhere you perform a task, and<br />

they improve readability by isolating code that performs specific tasks.<br />

This chapter introduces the syntaxof function calls and function definitions and discusses<br />

how to manage variables in functions and pass values to functions (including<br />

pass-by-value and pass-by-reference). It also covers variable functions and anonymous<br />

functions.<br />

Calling a Function<br />

Functions in a <strong>PHP</strong> program can be either built-in (or, by being in an extension,<br />

effectively built-in) or user-defined. Regardless of their source, all functions are evaluated<br />

in the same way:<br />

$some_value = function_name( [ parameter, ... ] );<br />

The number of parameters a function requires differs from function to function (and,<br />

as we’ll see later, may even vary for the same function). The parameters supplied to<br />

the function may be any valid expression and should be in the specific order<br />

expected by the function. A function’s documentation will tell you what parameters<br />

the function expects and what values you can expect to be returned.<br />

Here are some examples of functions:<br />

// strlen( ) is a built-in function that returns the length of a string<br />

$length = strlen("<strong>PHP</strong>"); // $length is now 3<br />

// sin() and asin( ) are the sine and arcsine math functions<br />

$result = sin(asin(1)); // $result is the sine of arcsin(1), or 1.0<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

61

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

Saved successfully!

Ooh no, something went wrong!