结合两个参考变量

时间:2017-02-21 14:41:49

标签: php

是否有可能“粘合”两个参考变量?

例如

$more = &$first.':'.&$second;

使用此功能,我收到语法错误,意外&

完整代码

$numOf = isset($_GET['numof']) ? $_GET['numof'] : 'x';

if($numOf == 1) {

$more = &$first;

} else if($numOf == 2) {

$more = &$first.':'.&$second;

} else {

$more = '';

}

$results = array(); // array with results from database

foreach($results as $res) {

$first = $res[0];
$second = $res[1];

echo $more.$res[3];

}

4 个答案:

答案 0 :(得分:1)

您可以做的一件事是:

$ar = array(&$first, &$second);
$more = implode(":", $ar);

答案 1 :(得分:1)

你应该使用Closure来实现你想要的。的确,你需要PHP 7(可能是5.6,不能告诉我无法测试)才能达到预期的效果。这是一个例子:

<?php
$first = "a";
$second = "b";
$more = function(){ global $first,$second; return $first.$second; };

echo $more()."<br>"; // This will output ab
$first = "b";
echo $more(); // This will output bb

答案 2 :(得分:0)

不直接,至少不是我所知道的。 可以做的是使用自动组合值的方法创建一个类。如果你只想要字符串输出,你可以使用魔术方法__tostring,这样你就可以直接使用该类:

class combiner
{
    private $a;
    private $b;
    public function __construct(&$a, &$b)
    {
        $this->a = &$a;
        $this->b = &$b;
    }
    public function __tostring() {
        return $this->a.":".$this->b;
    }
}

$ta = "A";
$tb = "B";
$combined = new combiner($ta, $tb);
echo $combined; //A:B
$ta = "C";
echo $combined; //C:B

答案 3 :(得分:0)

您可以通过以下方式获得所需的结果:

<?php

function more($first, $second){
    if(!empty($_GET['numof'])){
        if($_GET['numof']==1)
            return $first;
        elseif($_GET['numof']==2)
            return $first.':'.$second
    }
    return '';
}

$results = array(); // array with results from database

foreach($results as $res) {
    $first = $res[0];
    $second = $res[1];
    echo more($first, $second).$res[3];
}
相关问题