Notice: Only variables should be passed by reference

Case showcase-api项目代码片段

<?php
$feature = Format::toStruct(new FeatureWithIntroAndImgUrl(), Map::getFeature(), $val);
<?php
public static function toStruct(TStruct &$struct, array $dbMap, array $data);

errno: 8, message: Only variables should be passed by reference

分析

以下代码在PHP7抛出NOTICE错误

<?php
class C{ }
function f(C &$c) {}
f(new C);
Output for 7.0.7 - 7.1.4
Notice: Only variables should be passed by reference in /in/mDpGv on line 4

Output for 5.6.0 - 5.6.30, hhvm-3.12.14 - 3.18.1, 7.0.0 - 7.0.6

Fix

<?php
class C{ }
function f(C $c) {}
f(new C);

// or

function f(C &$c) {}
$c = new C;
f($c);

参考: language.references.pass

The following things can be passed by reference:

Variables, i.e. foo($a) New statements, i.e. foo(new foobar()) References returned from functions, i.e.:

❗️❗️❗️No other expressions should be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid:

<?php
function foo(&$var)
{
    $var++;
}
function bar() // Note the missing &
{
    $a = 5;
    return $a;
}
foo(bar()); // Produces fatal error as of PHP 5.0.5, strict standards notice
            // as of PHP 5.1.1, and notice as of PHP 7.0.0

foo($a = 5); // Expression, not variable
foo(5); // Produces fatal error

results matching ""

    No results matching ""