-1

i have below a function called test thats being called, and just echos "test" keeping it simple, for this question.

test();

function test() {
    echo "do something";
}

However i want to try and make the function dynamic if thats the right choice of words.

I have a list of records in a database, and based on each record, i may want a different function to process that record, the idea then is to have a field in the database which would be function_name, i then use that field to some how call that function.

Like this

test();

$function_name = "test";
function $function_name() {
    echo "do something here";
}

the only way i can think to get around this is to use switch/case but that is going to cause me other issues down the line.

  • http://php.net/manual/en/functions.variable-functions.php – Funk Forty Niner Jun 23 '15 at 15:37
  • Why would you want to do this? – John Conde Jun 23 '15 at 15:37
  • see http://stackoverflow.com/q/7213825/ and http://stackoverflow.com/q/1005857/ - http://php.net/manual/en/functions.variable-functions.php and http://php.net/manual/en/function.call-user-func.php which are inside those Q's & A's. One of those is probably a duplicate of. – Funk Forty Niner Jun 23 '15 at 15:39
  • 1
    *There's always a method to one's madness* - @JohnConde – Funk Forty Niner Jun 23 '15 at 15:40
  • @ John Conde, as explained i have a database with a lot of records, and each record is related to a url and to data mine it. I then have different functions to deal with the different websites im wanting to mine, so using a job server i send the url and function name to process the html to the worker. –  Jun 23 '15 at 15:43
  • 3
    Often times that madness is called an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – John Conde Jun 23 '15 at 15:44

2 Answers2

1

The function has to be defined with a specific name but you can call it using a variable that contains its name like so :-

<?php
function name() {
    echo "name";
}

$func_name = 'name';

// its always a good idea to check that function 
// actually exists before calling it.
if (function_exists($func_name)) {
    $func_name();
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
0

Use closures for this:

<?php

$funcName = 'test';

$$funcName = function ()
{
    echo 'Do something';
};

$test(); // 'Do something'
$$funcName(); // 'Do something'
Kevin Nagurski
  • 1,889
  • 11
  • 24
  • hi, how does this differ to RiggsFolly's answer? –  Jun 23 '15 at 16:03
  • @Skydiver1977 the main difference is that the function. Is being initialised with a dynamic name, not just being called that way. After that, they both are pretty much the same just an alternative – Kevin Nagurski Jun 23 '15 at 16:05