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

6

2 Answers 2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

Use closures for this:

<?php

$funcName = 'test';

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

$test(); // 'Do something'
$$funcName(); // 'Do something'

2 Comments

hi, how does this differ to RiggsFolly's answer?
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.