PHP通过引用传递?

时间:2014-07-17 20:32:44

标签: php pass-by-reference

前段时间,我在php上写了一个网站,现在正在我的网络服务器上设置它。回到我写的时候,一切都很好,但现在,它产生了这些错误:

Strict Standards: Only variables should be passed by reference in /home/dragonto/public_html/source/navbar.php on line 4
class="current">Home Strict Standards: Only variables should be passed by reference in /home/dragonto/public_html/source/navbar.php on line 4
>About Strict Standards: Only variables should be passed by reference in /home/dragonto/public_html/source/navbar.php on line 4
>Contact Us Strict Standards: Only variables should be passed by reference in /home/dragonto/public_html/source/navbar.php on line 4
>Projects Strict Standards: Only variables should be passed by reference in /home/dragonto/public_html/source/navbar.php on line 4
>Tutorials 

我不确定这些是什么意思。我做过关于在PHP中传递ref的研究,并且它看起来我没有做出任何违规行为。这是有问题的剧本:

<?php
    function GetScriptName()
    {
        return end(explode("/", $_SERVER['SCRIPT_FILENAME']));
    }

    $Links = array(
                1 => array(1 => "Home",       2 =>     "index.php"),
                2 => array(1 => "About",      2 =>     "about.php"),
                3 => array(1 => "Contact Us", 2 =>   "contact.php"),
                4 => array(1 => "Projects",   2 =>  "projects.php"),
                5 => array(1 => "Tutorials",  2 => "tutorials.php")
            );

    echo "<nav>\n<ul>\n";

    foreach($Links as &$Link)
    {
        echo "<li";

        if($Link[2] == GetScriptName())
            echo " class=\"current\"";

        echo "><a href=\"" . $Link[2] . "\">" . $Link[1] . "</a></li>\n";
    }

    echo "</ul>\n</nav>\n";
?>

1 个答案:

答案 0 :(得分:7)

问题在于对end的调用,它通过引用获取其参数。但是在这个片段中,实际参数不是变量,因此不能通过引用传递。严格的标准警告抱怨这一点。

此警告非常温和,虽然您不应该在任何情况下生成代码生成警告,但实际上您可以忽略它(代码仍然按预期工作)。

但通过手动引入变量来关闭它也非常容易:

$arr = explode("/", $_SERVER['SCRIPT_FILENAME']);
return end($arr);

在这种特殊情况下,最好通过使用end之外的其他内容来解决问题 - 这种内容在语义上更准确,例如

return basename($_SERVER['SCRIPT_FILENAME']);