Functions – PHP Certification Exam Series [2]

Introduction: This is the second part of my study notes for the Zend PHP Certification Exam. You can read more about my PHP Certification exam journey here.
Article Highlights
Function Basics
<?php
function name( $arg1, $arg2, … $arg_n ) { }
name( $arg1, $arg2, … $arg_m ) { } // when calling the function, $arg_m needs not be all defined in the function header
$a = name; $a($arg1, $arg2); // variable function
- Any valid PHP code may appear inside a function, even other functions and class definitions.
- Functions need NOT be defined before they are referenced (but must be defined somewhat), except the function is defined in a conditional clause
- Defined function cannot be redefined, otherwise server error will be thrown
- All functions and classes in PHP have the global scope – they can be called outside a function even if they were defined inside and vice versa.
- function names are not case-sensitive
- types: built-in, user-defined, externally provided (in extensions)
- global $id; or $GLOBALS[‘id’] to call global variables (actually global $id is a shortcut to $var = & $GLOBALS[“var”]; )
- PHP 5 allows default values to be specified for parameters even when they are declared as by-reference (if a variable is not passed in, a new one will be created)
- In PHP5 Objects are always passed ByRef unless you explicitly clone it.
- recursive functions are allowed (e.g. function recursion($a) { if($a<10){recursion($a+1);} }), care must be taken to avoid running time to be too long
- to check for the existence of a function, use function_exists($function_name);
- $arr = get_defined_functions ( ) : to get all the functions, $arr[‘user’] contains user-defined functions
<?php
function printList($string, $count = 5){ } // default values must be put to the right
function printList($count=5, $string){ } is invalid
function newTo5(&$number = 2){ } // as PHP 5, default value may be assigned to reference
function fun($x, $x=1, $x=2){ return $x;}; echo fun(3); // gives 2, as arguments are evaluated from left to right
function fun($x){ return $x;}; echo fun(3,4,5,6,7,8); // gives 3, warning will be issued only when fewer arguments are supplied than defined in the function header
// inside a function, cannot be put in an inc file alone from PHP 5.3 (scope warning), used for variable-length argument list which is allowed for any function in PHP
$a = func_get_args (); // all arguments in an array
int func_num_args (void)
mixed func_get_arg ( int $arg_num ) // 0, 1, … if func_get_arg(10) will return 0 if 10 not exists
Return
- values are returned by using the optional return statement
- If the parameters given to a function are not what it expects, such as passing an array where a string is expected, the return value of the function is undefined
- any type may be returned, including arrays and objects
- return causes the function to end its execution immediately and pass control back to the line from which it was called
- if return is not present in the function, null is returned
By reference
<?php
function &name() { return $someref; }
$newref = & name();
- allows you to return a variable as the result of the function, instead of a copy
- is used for things like resources and when implementing the Factory pattern
- you must return a variable, not an expression or string
- function &hello() { return ‘hello’; } // invalid, a notice will be issued
- call-time pass-by-reference (i.e. & is not included in function definition but added when calling the function) is depreciated in PHP 5.3 (will issue fatal error in PHP 5.4)
Variable Functions
$func = 'foo'; $func('test'); // This calls foo('test');
$foo = new Foo(); $func='variable'; $foo->$func(); // This calls $foo->variable();
- if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it
- this can be used to implement callbacks, function tables, and so forth
- Variable functions won’t work with language constructs such as echo, print, unset(), isset(), empty(), include, require and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.
- Note this is invalid: $x = function fund($a){return $a;}; print $x(1);
Anonymous Functions (Lambda Functions) and Closures
PHP allows the creation of functions which have no specified name (disposable 1 time use only). They are most useful as the value of callback parameters, but they have many other uses. Anonymous functions can also be used as the values of variables.
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
}; // the trailing semicolon is NECESSARY
$greet('World');
$greet('PHP');
?>
It is possible to use func_num_args(), func_get_arg(), and func_get_args() from within the anonymous function. Use is_callable($ab) to test whether $ab is an anonymous function.
The create_function() function is used to create an anonymous function in PHP. This function call creates a new randomly named function and returns its name (as a string).
$foo = create_function('$x,$y', 'return $x*$y;'); // must be single quoted or escaped double quoted, otherwise variables will be evaluated
echo $foo(10); (echo $foo will give lambda_1)
A closure is any function which closes over the environment in which it was defined. This means that it can access variables not in its parameter list.
The predefined final class Closure was introduced in PHP 5.3.0. It is used for internal implementation of anonymous functions. The class has a constructor forbidding the manual creation of the object (issues E_RECOVERABLE_ERROR) and the __invoke method with the calling magic. The closure can inherit variables from the parent scope.
<?php
$callback = // defined within the class Cart and the public function getTotal($tax)
function ($quantity, $product) use ($tax, &$total) // access variables from the parent
{
$pricePerItem = constant(__CLASS__ . "::PRICE_" .strtoupper($product));
$total += ($pricePerItem * $quantity) * ($tax + 1.0);
};
array_walk($this->products, $callback);
You can read more about my PHP Certification exam journey here.
Hi, my name is Edward Chung, PMP, PMI-ACP®, ITIL® Foundation. Like most of us, I am a working professional pursuing career advancements through Certifications. As I am having a full-time job and a family with 3 kids, I need to pursue professional certifications in the most effective way (i.e. with the least amount of time). I share my exam tips here in the hope of helping fellow Certification aspirants!