Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Russelmhardy's avatar

function exists and execute it

hi guys i wanna ask u i have a class and i wanna check a function inside my class if exist then execute it with method dynamically

My Code :

foreach ($this->functions[substr($this->tram, 6, 2)]['function'] as $key => $value){

       if(function_exists($key)) {
            $key(); //not working 
        }
   
        else {
            
            echo " Les fonction ".$key." ne sont pas disponibles.<br />\n";
        }
        }  
}
0 likes
14 replies
vincent15000's avatar

Hello, here $key is only a string.

Have you tried to use call_user_func() php function ?

tisuchi's avatar

@russelmhardy You can simply try this-

    public function foo()
    {
        dd("I am calling");
    }

    public function bar()
    {
        $key = 'foo';

        if(function_exists($key())) {
            $key();
        }
    }
tisuchi's avatar

@vincent15000

I think he checked the function without ().

function_exists($key)

But I suggest this-

function_exists($key())
1 like
tisuchi's avatar

@russelmhardy

Probably the most proper way is using the curly brackets {$key}()?

if(function_exists({$key}())) {
1 like
vincent15000's avatar

@tisuchi I don't know this notation in this context. Curly brackets are often used to write a variable directly in another string.

$string = 'Hello {$my_variable}, how are you ?';
tisuchi's avatar

@vincent15000 I agree with you.

But I believe {} is also used to wrap your variable when you call it from the string.

1 like

Please or to participate in this conversation.