简体   繁体   中英

Strict Standards: Only variables should be passed by reference in going over array

The code below...

$msgArr = split("\n", $message);
$newMsg = "";
foreach ($msgArr as $msg){
    if (trim(end(split(":", $msg))) != '')
        $newMsg .= $msg . "\r\n";
}

Seems to generate the error: Strict Standards: Only variables should be passed by reference in /home/siteurl/public_html/questionnaire/full_questionnaire_submitted.php on line 1033

Any ideas why this is?

Many thanks in advance.

Following strict standards, you should only pass a variable to end() not a function return value directly. This is because end() consumes it's argument by reference. (Check @NiettheDarkAbsol's nice explanation)

This line:

if (trim(end(split(":", $msg))) != '')

should be:

$pieces = split(":", $msg);
if (trim(end($pieces)) !== '') 

end函数将您传递的数组的光标作为参数移动,如果您传递的是split的返回值,则不能通过引用传递。

end() has the following signature:

mixed end ( array &$array )

So it takes a reference as its argument. References work by pointing to a variable, rather than copying the variable's value (as would normally be the case), which means you cannot directly pass a function's return value to it, hence the error.

PHP has been programmed to handle this kind of thing gracefully, since it's a simple matter of creating an internal, temporary variable, so it will continue to work but you will get the Strict Standards error.

Since you want to get the trimmed text from the last : to the end of the string, consider:

$lastpiece = trim(substr(strrchr($msg,":"),1));

This uses strrchr to get everything from the last : to the end, substr to knock off that last : , before finally trim ming it.

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