简体   繁体   中英

proper way of calling a function from a different file in PHP

let's say I have a function as so

function something($variable){

   $variable = sanitize($variable);
   $variable1 = sanitize($Variable1);

 ......
}

When I call this function from a different file and pass 2 variables to it, would this be acceptable? Let's say I call in this fashion...

something($_GET['variable1'], $_POST['variable']);

Thank you!

Yes, as long as that file is included.

So say functions.php has your something() function. You would need to do:

include('/path/to/functions.php');
something($_GET['variable1'], $_POST['variable']);

It depends on how your files are tied together.

If you are using classes and organizing by that, you could declare this static and call it like:

yourClassName::something(variable1, variable2);

If you are just using includes to link the files, you should be able to do just as you described.

Yes, you could do that, but you need to include the file beforehand (using require , require_once , include or include_once ). Unlike other languages PHP won't complain that all the params haven't been described beforehand.

This would fail, though, as this specifies that it MUST receive 3 variables:

function something($var1, $var2, $var3) {
}

If you magically want to get all the parameters posted to a function, you can use func_get_args as so:

function something() {
    $arguments = array();

    foreach (func_get_args() as $argument) {
        $arguments[] = sanitize($argument);
    }

    print_r($arguments);
}

Here $arguments[0] is a sanitized version of $variable , and $arguments[1] is a sanitized version of $variable1 .

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