简体   繁体   中英

PHP Trim inside function

I have the following simple PHP script:

<?php

    function generate($test_var, trim($test_var2)) {
        echo $test_var2;
    }

    generate('value 1', ' value2');

?>

It's giving the following error:

PHP Parse error:  syntax error, unexpected '(', expecting '&' or T_VARIABLE 
in ** on line 3

I can't figure out why trim can't be used in this context.

You simply can't call a function inside the argument list of the definition of another function * . Perhaps you meant to do something like this:

function generate($test_var, $test_var2) {
    $test_var2 = trim($test_var2);
    echo $test_var2;
}

* Note that you can use the array language construct when declaring the default value of parameter, although this isn't a function.

Further Reading

Another function is not valid within the list of parameters in a function's definition in PHP. The operative words being within the list of parameters in a function's definition ; you can read about the structure of a function here: http://www.php.net/manual/en/functions.arguments.php

Having said that, when invoking a function as mentioned below in the comments by pswg you can pass a function as an argument in most cases as a callback .

Eg

Valid:

function foo($bar, $baz) {
   // Do something
}

...
foo('Hello', trim('World '));

Invalid:

function foo($bar, trim($baz)) {
   // Do something
}

...
foo('Hello', 'World ');

Simply put:

PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are also supported, see also the function references for func_num_args(), func_get_arg(), and func_get_args() for more information.

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