Variable as a function-call

Posted by Thomas on December 14th 2008 - Tags: ,

In PHP there is one really cool thing you can do. You can use a variable as a function call. Microsoft created a sort of a similar thing in C#, but it’s not as easy to use.

It’s easier to show you with an example then trying to explain it, so that is what I will do

<?php
  function foo()
  {
    echo "Hello World!";
  }

  $bar = "foo";
  $bar(); // this calls foo()
?>

Neat eh?

This can be used to call different classes depending on the URI. New example for this:

<?php

  $uri = explode('/', $_SERVER['REQUEST_URI']);

  if( is_file($publicClassesPath . "/" . $this->uri[1] . ".php"))
  {
    include_once( $publicClassesPath. "/" . $this->uri[1] . ".php");

    $RunningClass = new $uri[1](); // initiate the class and bind an instance
                                   // to the variable $RunningClass
  }
?>

There are no comments yet, be the first to voice your opinion!

Leave a Reply