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

filipe1221's avatar

Check if function exists

Hello.. i want create function width 1 parameter wil be the name of the file example:

function a(test.php){ //Check if function translate exists in file test.php }

i want to check if passed file if a function "translate " was being called

0 likes
6 replies
filipe1221's avatar

yah but its want specify a file and That function should open this file search a function inside there

Cronix's avatar

I don't think there's anything native that will do this. PHP only knows about functions that are defined, which means the file has to be executed to bring it "into php".

You'd probably have to manually read the file, and use regex to see if function {name} exists in the text of the file.

You could also just use php's regular include function to bring the file into php and then use if (function_exists('functionName')), but that could be very dangerous if the php file you're checking in could contain malicious code. Treating it as a text file and seeing if text is present is a lot safer.

jlrdw's avatar

You could use a debug_backtrace. A while back I had to get the model name from a controller name, so I did:

<?php

namespace App\Helpers;

class DBS
{

    public static function __callStatic($method, $params)
    {
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
        
        if (isset($trace[1]['class'])) {
            $class = $trace[1]['class'];
            //echo $class;
        $slh = strrpos($class, "\") + 1;
        } else {
            return null;
        }
        $model = "\App\Models\SMVC" . "\" . substr($class, $slh, -10) . "Model";
        $instance = new $model();

        return call_user_func_array(array($instance, $method), $params);
    }

}

Maybe that could be adapted. This works to see what is in the stack. In my case say a controller named AccountController was used, I needed the name

Account from it.

Long story, just learn about how to use debug_backtrace

jlrdw's avatar

Well sorry I mis-understood. But the developer should know if they have a function in a file should they not.

jlrdw's avatar

i want to check if passed file if a function "translate " was being called

was being called

debug_backtrace should tell him if that was called. I haven't used debug_backtrace a lot, but I have played around with it, pretty neat technique.

Please or to participate in this conversation.