Zend PHP 5 – Functions – Syntax

Functions are covered within the Zend PHP study guide. Functions are packages of code that serve as instructions to execute an action.

Any valid PHP code can reside in a function.

You can define a function like the example written below.

<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
    echo "Example function.\n";
    return $retval;
}

Functions do not need to be defined before they are referenced, unless a scenario occurs when a function is conditionally defined.

<?php

$makefoo = true;

/* We can't call foo() from here 
   since it doesn't exist yet,
   but we can call bar() */

bar();

if ($makefoo) {
  function foo()
  {
    echo "I don't exist until program execution reaches me.\n";
  }
}

/* Now we can safely call foo()
   since $makefoo evaluated to true */

if ($makefoo) foo();

function bar() 
{
  echo "I exist immediately upon program start.\n";
}

This outputs:

I exist immediately upon program start.
I don't exist until program execution reaches me.

Function names are case-insensitive, though it is usually good form to call functions as they appear in their declaration.

Function parameters and return values are optional, however it is advised to set a default parameter to avoid generating a PHP warning like the following:

<?php
function myFunction($p)
{
    return $p;
}

$x = myFunction("ABC"); // x = "ABC"
$x = myFunction();      // Warning

function myOtherFunction($p = "ABC")
{
    return $p;
}

$x = myOtherFunction("DEF"); // x = "DEF"
$x = myOtherFunction();      // x = "ABC"

PHP comes standard with many in-built functions and constructs. T

here are also functions that require specific PHP extensions compiled in, otherwise fatal “undefined function” errors will appear. For example, the mysqli_connect() function can be used to connect to a database.

Use the phpinfo() or get_loaded_extensions() function which will show the extensions that are loaded into PHP.

Note: This article is based on PHP version 5.5.