Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function without knowing it's name

Tags:

php

I want to create a function in PHP and to call it without knowing the function's name.

Is this possible?

Example:

<?php

     $functionName = "someName";
     $this->$functionName();
     function someName(){
         echo("Print Message");
     }
?>
like image 363
Damian SIlvera Avatar asked Jan 31 '26 07:01

Damian SIlvera


1 Answers

It looks like you want call_user_func().

$functionName = "someName";
call_user_func($functionName); //calls `someName()`

Can be used like the following where the output is the printed message "Hello, World!":

function someName($val){
    return $val;
}

$functionName = "someName";
echo call_user_func($functionName, "Hello, World!");

http://ideone.com/Kw5jp

Note: If you're using newer versions of PHP, you can also use callables as @J.Bruni pointed out:

$functionName = "someName";
$functionName(); //also calls `someName()`
like image 198
jeremy Avatar answered Feb 01 '26 22:02

jeremy