04 September 2011

How to call a variable as a function in php

Code Optimization had always been major concern for all the Software developers. Today through this post of mine, you can optimize your code to a great extent in a situation, where you want to call different functions according to certain conditions.

Say, you want to call a certain function according to certain value of variable which in turns comes from database. Now if you will follow normal approach, your code will become too large to be managed, in addition of writing separate function, you will write numerous conditions, which will make your code quite typical.

In order to make it simple, we will just use an inbuilt function of PHP named “call_user_func” through which you can use that particular variable as a function.

I will explain you its functionality using following code.
<?php
/*
Say I wrote a simple function to increment a value based on database value ie whether to decrement or increment a value
*/
function increment(&$var) {
    $var++;
}

$a = 0;
$database_value = $bla bla
call_user_func($database_value$a);
// here second parameters indicates the parameter to be passed
echo $a."\n";
?>

Now the concept is you will just add a separate column in database which will store the name of function to be called, say increment or decrement. Now each time you want to increment or decrement, just fetch function name from database and call it using this call_user_func .