PHP Function & Exception

PHP Function

PHP function passing parameters by value

function m1($p1, $p2)
{
    echo $p1;
    return $p2;
}

m1('hello ', 3);

PHP function passing parameters by reference

function m1(&$p1)
{
   $p1 = "Changed";
}

$v1 = 'hello';
m1($v1);
echo $v1;                                   # 'Changed'

PHP function return by reference

class MyClass {
    public $v1 = "say a huge returned data";

    public function &getV1() {
        return $this->v1;                   # Return as a reference
    }
}
$o = new MyClass;
$result = &$o->getV1();                     # $result is a reference to $o->v1
                                            # To avoid extra copy for large data
$o->v1 = 20;
echo $result;                               # 20

PHP return multiple values in function

function get_results()
{
    return array (0, 1, 2, 4);
}
list ($v1, $v2, $v3, $v4) = get_results();

PHP Function Parameters

Type hinting

function m1(MyClass $p)                     # Only accept $p to be MyClass
{                                           # Type hinting support object class or array parameter
  var_dump($p);
}

$v = new MyClass();
m1($v);                                     # Will throw error if $v is not of type MyClass

PHP default argument

function m1($p1, $p2='some value')

Parameter(s) with default value(s) must be on the right side of non-default arguments

Default parameter's value must be a constant expression

PHP variable number of arguments

function m1()
{
     $num = func_num_args();                     # Get number of arguments
     for ($i=0; $i<$num; $i++) {
         echo "Argument: " , func_get_arg($i);   # Get argument
     }
}

m1 ("p1", "p2" , "p3");

PHP missing arguments

function m1($p1, $p2) {
}

m1(4);                                           # $p2 is unset

Method Signature in the PHP documentation

string gettype( mixed $var )
  • number: Take numeric parameter
  • mixed: The method takes parameter of different type (String, array, etc ...)
  • callback: take a function callback

Calling Variable Function in PHP

Dynamic function calling in PHP

function hello()
{
   echo 'hello';
}

function world()
{
   echo 'world';
}

$func = 'hello';
$func();                                   # call hello()

$func = 'world';
$func();                                   # call world()

if(function_exists($func)) {
   $func();                                # Call it only if it exists
}
class Messenger
{
    function hello()
    {
        $func = 'world';
        $this->$func();               # Calling world()
    }

    function world()
    {
        echo "world";
    }
}

$o = new Messenger();
$o->hello();

Conditional Function

Declare PHP function conditionally

if ($validate) {
  function validateData()
  {
     ...
  }
}

if ($validate) validateData();

Calling PHP Function Programmatic

Calling PHP function in runtime

function hello() {
    echo 'hello';
}

class Messenger {
    static function hello() {
        echo 'hello';
    }
}

call_user_func('hello');                       # Pass the 'hello' function callback as a parameter

call_user_func('Messenger::hello');            # Pass a static class function
call_user_func(array('Messenger', 'hello'));

$o = new Messenger();
call_user_func(array($o, 'hello'));

Calling PHP function taking parameter

call_user_func('my_method', $p1, $p2);
call_user_func('my_method', array(&$p1, &$p2));
Using Closure (PHP 5.3 or above)
$square = function ($v)
{
    return $v * $v;
};

$p = $square(3);                                    # Call the closure/anonymous function

$data = range(1, 5);

$result = array_map($square, $data);                # Apply a function to an array

var_dump($result);  # array(5) { [0]=> int(1) [1]=> int(4) [2]=> int(9) [3]=> int(16) [4]=> int(25) }

PHP Exception Handling

try {
  throw new Exception('Some error');         # Throw an exception
} catch (Exception $ex) {                    # Catch the exception
  echo 'Recover from error';
  throw $ex;                                 # Re-throw it
}

Built-in PHP Exception

  • Exception
  • ErrorException
Extending PHP Exception
class MyException extends Exception
{
    public function __construct($message, $code = 0, Exception $previous = null) {
        parent::__construct($message, $code, $previous);
    }

    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }
}

$ex = new MyException('Failure');
throw $ex;

PHP Error Throwing & Handling

Throw an exception

function division($a, $b) {
  if ($b == 0) {
     # Trigger an error
     trigger_error('Divided by zero', E_USER_ERROR);    # Trigger an error
  }

  return($a / $b);
}

Set an PHP error handler

function error_handler($error, $error_string, $filename, $line, $symbols) {

   # Log error
   error_log('Some error happen', 0);

   ...
}

set_error_handler('error_handler');
$a = 4/0;                              # Trigger an error
restore_error_handler();               # Restore the original handler

Built-in Function

Function Example Description
empty !empty($_POST['param1']) Check if parameter is empty including empty string, empty array , 0, '0', NULL or FALSE
is_null is_null($value) Is it NULL
isset isset($value) Has value been set
Function Description
debug_zval_dump Dumps a zend value
doubleval Float value
empty Variable is empty
floatval Float value
get_defined_vars All defined variables
get_resource_type The resource type
gettype Type of a variable
import_request_variables Import GET/POST/Cookie variables into the global scope
intval Integer value
print_r Print a variable
serialize Serialize
settype Set the type of a variable
strval Get string value
unserialize UN-serialize
unset Unset a variable
var_dump Dumps a variable
var_export Outputs a string representation of a variable
Debugging Description
debug_backtrace Generate backtrace
debug_print_backtrace Print backtrace
error_get_last Get last error
error_log Log error
error_reporting Configure PHP error level
restore_error_handler Restores the previous error handler
restore_exception_handler Restores the previously defined exception handler
set_error_handler Sets an error handler
set_exception_handler Sets an exception handler
trigger_error Generates an error
user_error Generates an error

Windows

PHP can use the forward slash as Windows directory separator

$f = fopen('c:/dev/test.txt', 'r');