O'Reilly logo

PHP 7 Programming Cookbook by Doug Bierer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required