Web Development

What is a Function in PHP

A function is a named block of code that performs a specific task, possibly acting upon a set of values given to it, or parameters, and possibly returning a single value. Functions save on compile time—no matter how many times you call them, functions are compiled only once for the page. They also improve reliability by allowing you to fix any bugs in one place, rather than everywhere you perform a task, and they improve read-ability by isolating code that performs specific tasks.

Calling Functions

Functions in a PHP program can be built-in (or, by being in an extension, effectively built-in) or user-defined. Regardless of their source, all functions are evaluated in the same way:

$someValue = function_name( [ parameter, … ] );

The number of parameters a function requires differs from function to function. The parameters supplied to the function may be any valid expression and must be in the specific order expected by the function. If the parameters are given out of order, the function may still run by a fluke, but it’s basically a case of garbage in = garbage out. A function’s documentation will tell you what parameters the function expects and what values you can expect to be returned.

Built-in PHP Functions

PHP’s many built-in functions are one reason why PHP is so powerful and useful. The functions included with PHP are normal functions. They’re no different than functions you create yourself. It’s just that PHP has already done all the work for you.
You can use the built-in PHP functions the same way you call functions you create yourself. You use the function name and pass any values the function needs. We discuss specific PHP functions throughout the book. For instance, we discuss several functions that you can use to check whether a variable exists or whether it’s empty. Here are a couple of those functions:

isset($varname )

empty ($varname)

The PHP online documentation describes all the built-in functions at www. php. net /manual /en/funcref.php. In addition, the PHP documentation provides a search function that’s very useful when you remember the name of the function but can’t remember the exact syntax. Type the function name in the Search For text box at the top of the Web page and choose Function List from the drop-down list.

Leave a Reply

Your email address will not be published. Required fields are marked *