PHP函数引用

时间:2014-11-28 07:37:59

标签: php reference

我试图修改通过引用传递的变量时出现致命错误。我已经查看了有关引用传递PHP函数的文档,但我无法弄清楚我做了哪些不同的事情。我发现如果我删除t0和t1上的引用(&符号),那么我可以分配它而没有致命错误;但是,我需要修改t0和t1进行跟踪。如果重要的话,我使用的是PHP 5.5.9。

我的问题的背景是光线跟踪器,并且在球体内部交叉方法。 函数调用如下:

if($obj->intersect($ray, $t0, $t1)) { ... }

交叉方法如下:

function intersect(Ray $ray, &$t0, &$t1) {
// if discrim is >= 0 go on
$discrim = $b * $b - (4.0 * $a * $c);
if($discrim >= 0) {
$t0 = (-1.0 * $b - sqrt($discrim)) / (2.0 * $a); // error ... }

如果我将函数定义更改为:

,程序将运行
function intersect(Ray $ray, $t0, $t1) { ... 

1 个答案:

答案 0 :(得分:0)

引用的替代方法是使函数返回$t0$t1的值:

// Modify the function to return the new values of $t0 and $t1
function intersect(Ray $ray, $t0, $t1)
{
    // Function code here, including the modification of $t0 and $t1

    // $result is the value previously returned by function (boolean, I guess)
    return array($result, $t0, $t1);
}


// Modify the code that calls the function to match its new behaviour
list($res, $t0, $t1) = $obj->intersect($ray, $t0, $t1);
if ($res) { ... }

如果函数不使用参数$t0$t1的初始值,则可以从参数列表中删除它们。