简体   繁体   中英

How to include file when a function called in php

I know this is a totally rubbish kind of question but i am totally confuse and i don't know how to include file when a function called in php.

for example i have a dir name as Function which is containing 100's of file with the function name like myfunction.php and this file has myfunction();

so when i called this function like

include 'Function/'.$functionName.'.php'; // here file should auto include.
myfunction(); // i called this function here so when i called this function then myfunction.php file should auto include in above line 

is there any way to include file automatically. please suggest me a way.

Calling an undefined function throws an undefined error, which will halt execution when it happens. Even if you could catch the error, you couldn't then return the function output to the original variable.

My recommendation, include all functions at the start of the page:

foreach (glob("Function/*.php") as $filename)
{
    include $filename;
}

Otherwise, you'd have to do something like this, manually for each call:

try {
    $ret = example_function();
} catch ( Exception $e) {
    include('Function/example_function.php');
    $ret = example_function();
}

You could however, create a custom function which would do that:

function myFunction()
{
    $args = func_get_args();

    $func_name = array_shift($args);

    if ( !function_exists($func_name) ) {
        include('Function/' . $func_name . '.php');
    }

    return call_user_func_array($func_name, $args);
}

You would then have to call your functions with myFunction('testFunction', $param1, $param2) .

If you're loading classes, this becomes easier. You can use PHP autoloading to accomplish this task:

Many developers writing object-oriented applications create one PHP source file per class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).

In PHP 5, this is no longer necessary. The spl_autoload_register() function registers any number of autoloaders, enabling for classes and interfaces to be automatically loaded if they are currently not defined. By registering autoloaders, PHP is given a Last Chance to load the class or interface before it fails with an error.

You can try to use method overloading, __call

class MethodTest
{
    public function __call($functionName, $arguments)
    {
        include 'Function/'.$functionName.'.php';
        return $functionName($arguments); 
    }

}


$obj = new MethodTest;
$obj->myCustomFunc("myCustomParams")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM