Last Updated: February 25, 2016
·
817
· shawnrice

Create a hookable function in PHP

Variable functions can be fun and allow others to extend your code.

Here's how to have fun with them.

Start simple first

Imagine a few files

// main.php

require_once( 'extended_functions.php' );
 $suffixes = array( "_custom",
                    "_custom1",
                    "_custom2",
 );

 run_variable_functions( $suffixes , "my_arg" );

 function run_variable_functions( $suffixes , $arg ) {
   foreach ( $suffixes as $suffix ) :

     $function = "my_variable_function$suffix";

     if ( function_exists( $function ) )
       $function( $arg );

   endforeach;
 }

And

// extended_functions.php
 function my_variable_function_custom ( $arg ) {
   // Some code goes here.
 }
 function my_variable_function_custom1 ( $arg ) {
   // Some code goes here.
 }
 function my_variable_function_custom2 ( $arg ) {
   // Some code goes here.
 }

So, here we'd have a few functions defined in the "extended functions.php" file, and then the one that deals with everything is in "main.php."

Let's make it better

You can make this more dynamic by just having a folder where all extension code goes and then grab each one little bit at a time.

So, let's start with new files:

main.php

 // main.php

$suffixes = array();
$extensions = scandir( '../extensions' );
foreach ( $extensions as $file ) :
  if ( strpos( $file , ".php" ) )
    include( "../$file" );
endforeach;

  run_variable_functions( $suffixes , "my_arg" );

  function run_variable_functions( $suffixes , $arg ) {
    foreach ( $suffixes as $suffix ) :

      $function = "my_variable_function_$suffix";

      if ( function_exists( $function ) )
        $function( $arg );

    endforeach;
  }

extension_one.php

// extension_one.php
if ( ! function_exists( 'my_variable_function_custom' ) ) {
  function my_variable_function_custom( $arg ) {
    // insert some code
  }
  $suffixes[] = "custom";
}

extension_two.php

// extension_two.php
if ( ! function_exists( 'my_variable_function_custom2' ) ) {
  function my_variable_function_custom2( $arg ) {
    // insert some code
  }
  $suffixes[] = "custom2";
}

So, you'll see that in main.php, all we do is create an empty array, then we scan the "extensions" directory and include only the ones with a php file extension After that, we have our run-variable-functions function that just goes through the suffixes array and tries to run each one.

The structure of the extension files is important in that they do two things: first, they define the function, and, second, they add an entry to the suffixes array. In order to prevent errors from clashing functions, it's best to wrap each function with the "if ( ! function_exists( function ) )" statement; otherwise your contributors can easily break your nice application.

You can do the same thing with class files.