呼叫时间传递参考pickle

时间:2013-08-05 12:30:21

标签: php pass-by-reference

让自己陷入困境。我们的主机已经将php升级到5.4,我们仍然在一个通过引用将参数传递给函数的类中运行一些代码(我们没有编写),它看起来像这样:

$func_args = '';

// Make $row[0], $row[1] accessible by using $C1, $C2 etc.
foreach ($row as $k => $v)
{
    ${'C'.($k+1)} = $v;

    $func_args .= "&\$C".($k+1).",";
}

// Give the user a chance to tweak the results with any function of their choice
// tweak functions are registered with $ez_results->register_function('func_name');
if ( is_array($this->tweak_functions) )
{
    // Tweak results with each registered function
    foreach ( $this->tweak_functions as $tweak_function )
    {
        // If function C1, C2, etc exists then run it
        if ( function_exists($tweak_function) )
        {
            eval("$tweak_function(".substr($func_args,0,-1).");");
        }
    }
}

函数在这里的类中进一步注册:

var $tweak_functions = array('tweak_results');

function register_function($function_name)
{
    $this->tweak_functions[] = $function_name;
}

这些函数是在外部PHP文件上定义的,如下所示:

function results_manipulation($news_id,$news_name,$news_seoname,$news_date2,$news_summary,$news_article,$news_url,$image_name,$image_thumb,$news_categories)
{
    global $i;

    if(!empty($image_thumb) && $i < 3 && empty($_GET['pg']) ){
        $image_thumb = '<div class="newsthumb" style="background-image:url('.$image_thumb.')" title="'.$image_name.'"></div>';
    }else{
        $image_thumb = '';
    }

    $i++;
}

我看了很多类似的问题,并试图找到一种替代代码并保持一切正常但没有任何成功的方法。有人能指出我正确的方向吗?

非常感谢

3 个答案:

答案 0 :(得分:1)

我会更改所有tweak函数的签名,以在参数列表中包含引用表示法,并将其从参数列表中删除。

  function someTweakFunction(&$a, &$b, &$c);

如果你可以删除eval代码也是一件好事。在这种特殊情况下,它似乎并不危险,但也不需要。您可以使用call_user_func_array。

当你构建参数列表时,创建一个参数数组而不是它们的字符串。

$func_args = array();

// Make $row[0], $row[1] accessible by using $C1, $C2 etc.
foreach ($row as $k => $v)
{
    $func_args[] = &$v;
}
if ( is_array($this->tweak_functions) )
{
    // Tweak results with each registered function
    foreach ( $this->tweak_functions as $tweak_function )
    {
        // If function C1, C2, etc exists then run it
        if ( function_exists($tweak_function) )
        {
            call_user_func_array($tweak_function, $func_args);
        }
    }
}

答案 1 :(得分:1)

我有同样的问题(使用ez_results),我解决了它。也许有人会喜欢这个有用的。

这一行

//old    
$func_args .= "&\$C".($k+1).",";

更改为:

//new
$func_args .= "\$C".($k+1).",";

此外,您使用ezr-&gt; register_function(“my_function”)

的功能
//old
my_function($arg1, $arg2, $arg3...)

必须改变(在每个参数前添加'&amp;'):

//new
my_function(&$arg1, &$arg2, &$arg3...)

答案 2 :(得分:0)

我最终完全重写了该功能,并使用重新编写的代码更新了所有网站。

感谢所有提出建议的人最终虽然改造了我们所拥有的只是延长痛苦的时间:在某个阶段需要完全重写。