Chapter 7. Function Reference


This chapter lists many of the most commonly used functions in PHP. Other functions are grouped together according to their topic, throughout this book.

Calling a function in PHP can be as simple as printing the name of a function with two parentheses, "( )", after it. However, many functions require you to give them input to work on, called parameters, which you send inside the parentheses. On top of that, nearly all functions have a return value, which is the result that the function sends back to your script. These return values can often be ignored, but most of the time, you will want to store them in a variable for later use:

     $string_length = strlen($mystring); 

You can also use these return values as parameters to other functions, like this:

     func1(func2(func3( ), func4( ))); 

Although most parameters are required, some are optional and don't need to be supplied. When optional parameters are omitted, PHP will assume a default value, which is usually good enough.

When you pass a parameter to a function, PHP copies it and uses that copy inside the function. This process is known as pass by value , because it is the value that is sent into the function rather than the variable. This means that when you pass variables to a function, it can change its copies of them however it likes, without affecting the original variables. To change this behavior, you can opt to pass by reference, which works in the same way as reference assigning for variablesPHP passes the actual variable into the function, and any changes you make will affect the original. This script demonstrates the difference:

     somefunc($foo);     somefunc($foo, $bar);     somefunc($foo, &$bar);     somefunc(&$foo, &$bar); 

The first line calls somefunc( ), passing in a copy of $foo; the second passes in copies of $foo and $bar; the third passes in a copy of $foo but the original $bar; and the last passes in both the original $foo and $bar. Passing by reference, as with $bar in line three and $foo and $bar in line four, means that these variables can be changed inside the function, which is often used as a way for functions to return information.

Variable variables were introduced in Chapter 5, and to complement them, PHP also has variable functions, allowing you to write code like this:

     $func = "sqrt";     print $func(49); 

PHP sees that you are calling a function using a variable, looks up the value of the variable, then calls the matching function. The code above will therefore return 7, the square root of 49.



PHP in a Nutshell
Ubuntu Unleashed
ISBN: 596100671
EAN: 2147483647
Year: 2003
Pages: 249

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net