1

I have a string variable

$worker_name = "video_convert"

I want to write a function with the name like the following

function video_convert(){
}

How can I do this in PHP? I tried

function eval($worker_name){
}

or

eval($worker_name) = function(){
}

But, it seems like it is not the correct way to do it in PHP.

2
  • what are you trying to do? Why calling the way you want? Commented Mar 7, 2016 at 6:33
  • You want to essentially randomize the names of your functions? This is a bad idea. What for‽ Commented Mar 7, 2016 at 7:36

4 Answers 4

3

You can do it as

$worker_name = 'video_convert';
$$worker_name = function() {
   echo 'hi';
};
$$worker_name();
Sign up to request clarification or add additional context in comments.

Comments

2

You could use call_user_func :

$worker_name ="video_convert"
function video_convert($text){
     echo "Hello $text\n";
}

call_user_func($worker_name, 'World');

OR you could use the way you tried:

$worker_name = 'video_convert';
function video_convert(){
    echo __METHOD__;
}
$worker_name();

OR like this:

$worker_name = function($text)
{
    echo 'Anonymous function call '.$text
};

$worker_name('Hello');

PHP is flexible.

Comments

1

You can do somewhat like as

$worker_name = "video_convert";

function video_convert(){
    echo "I've called a function using variable";
}

$worker_name();

Comments

1

If you want to use eval() function then use it by below way:-

$worker_name = "video_convert()";

function video_convert(){
    echo "Called";
}

eval("$worker_name;");

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.