开发者

why is php complaining about passing by reference in this code?

$test = 'love';
$eff = end(explode('ov',$test));

I can't figure it out; oddly enoug开发者_StackOverflow社区h, this doesn't get a complain:

$test = 'love';
$eff = current(explode('ov',$test));

The error I'm getting is: Strict: Only variables should be passed by reference


end changes the array's internal pointer by moving it to the end of the array. Thus, the parameter must be mutable (that is, a reference to an array) for that operation to be useful. This is why you receive the warning.

current doesn't touch the array at all; it only looks at the array. Thus, the parameter does not need to be mutable (thus can be passed by value) and the operation doesn't give you a warning.


end() modifies the array passed to it, by reference. Assign the explosion to a variable first so that end() has a reference it can modify.

$test = 'love';
$explosion = explode('ov',$test);
$eff = end($explosion);

end() only changes an internal pointer so it doesn't modify the contents of the array in anyway and you won't notice unless you're using the current(), each(), next() lot for iteration.

If this limitation of end() is annoying to you there are ways around it:

function last($array) { return end($array); }
$test = 'love';
$eff = last(explode('ov', $test));


The explode returns a temporary array, which you are not 'storing' to a variable but rather passing directly to end which expects a reference.

I believe the reason why current does not trigger the error is that it is non-mutating. Other mutating functions such as array_unshift and reset complain too.


<?php

error_reporting(E_STRICT);

$test = 'love';
$eff = end(explode('ov',$test));
var_dump($eff);

?>

it will work fine if your error reporting level is not set to E_STRICT.

See, when you have an temporary array returned, you cannot just set the internal pointer just like this. You need to set it to a variable first then move the internal pointer to the end using end().

This is true so for: reset(), next(), prev() and so on.

The following would work instead.

<?php

error_reporting(E_STRICT);

$test = 'love';
$a = explode('ov',$test);
$eff = end($a);
var_dump($eff);

?>

current() works because it does not move the internal pointer, but to get what the current element that the internal pointer is pointing at.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜