Developing functions

The most difficult aspect is deciding how to break up programming logic into functions. The mechanics of developing a function in PHP, on the other hand, are quite easy. Just use the function keyword, give it a name, and follow it with parentheses.

How to do it...

  1. The code itself goes inside curly braces as follows:
    function someName ($parameter)
    { 
      $result = 'INIT';
      // one or more statements which do something
      // to affect $result
      $result .= ' and also ' . $parameter;
      return $result; 
    }
  2. You can define one or more parameters. To make one of them optional, simply assign a default value. If you are not sure what default value to assign, use NULL:
    function someOtherName ($requiredParam, $optionalParam = NULL) { $result = 0; $result ...

Get PHP 7 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.