PHP 函数引用


PHP function references

我在尝试修改通过引用传递的变量时遇到致命错误。我已经查看了有关引用 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) { ... 

引用的替代方法是使函数返回 $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则可以将它们从参数列表中删除。