PHP 通过引用混淆 [英] PHP Pass by reference confusion

查看:54
本文介绍了PHP 通过引用混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

长话短说,我的框架中有以下功能:

To cut a long story short I have the following function as part of my framework:

public function use_parameters()
{
    $parameters = func_get_args();

    $stack = debug_backtrace();

    foreach($stack[0]['args'] as $key => &$parameter)
    {
        $parameter = array_shift($this->parameter_values);
    }
}

其中 $this->parameter_values = array('value1', 'value2', 'value3', 'value4', 'value5', ...);

Where $this->parameter_values = array('value1', 'value2', 'value3', 'value4', 'value5', ...);

在以下上下文中使用:

$instance->use_parameters(&$foo, &$bah);

分配:

$foo = 'value1';
$bah = 'value2';

再次调用

$instance->use_parameters(&$something); 

将设置

$something = 'value3'

等等.

从 5.3 开始,它将返回已弃用:不推荐使用调用时传递引用"警告.为了符合 5.3 的工作方式,我删除了 & 的结果:

As of 5.3 it would return a 'Deprecated: Call-time pass-by-reference has been deprecated' warning. In an effort to conform to the 5.3 way of working I removed the &'s resulting in:

$instance->use_parameters($foo, $bah);

不幸的是,这导致无法设置参数,我正在努力想出一个解决方案.

This unfortunately has caused the arguments not to be set and I'm struggling to come up with a solution.

我在 Apache/2.2.16 (Debian) 上运行 PHP v5.3.3-7 的价值是什么

For what its worth I'm running PHP v5.3.3-7 on Apache/2.2.16 (Debian)

任何帮助将不胜感激.

推荐答案

你不能在 PHP 中这样做,你在滥用引用的概念.您必须明确指定引用参数,尽管使用默认值.然而,您不希望使用 NULL 作为默认值,因为这是未分配的引用变量将被设置为的.所以你需要定义一些你知道不会被用作参数的常量,现在代码看起来像

You can't do that in PHP and you are abusing the concept of references. You have to specify the reference arguments explicitly, albeit with default values. However, you don't want to use NULL as a default as this is what an unassigned reference variable will be set to. So you need to define some constant that you know is not going to be used as a parameter, and now the code will look something like

    const dummy="^^missing^^";

    public function use_parameters(&$a, &$b=self::dummy, &$c=self::dummy ) {
        $a=array_shift($this->parameter_values);
        if($b!==self::dummy) $b=array_shift($this->parameter_values);
        if($c!==self::dummy) $c=array_shift($this->parameter_values);
        # add $d,$e,$f,... as required to a sensible max number
    }

请注意,因为您正确使用了引用,所以不需要 debug_backtrace() 问题.

Note that because you are using references properly, you don't need the debug_backtrace() botch.

这篇关于PHP 通过引用混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆