Php 组合两个参考变量
是否有可能“粘合”两个参考变量 比如说Php 组合两个参考变量,php,Php,是否有可能“粘合”两个参考变量 比如说 $more = &$first.':'.&$second; 使用此命令,我收到一个语法错误,一个意外的& 完整代码 $numOf = isset($_GET['numof']) ? $_GET['numof'] : 'x'; if($numOf == 1) { $more = &$first; } else if($numOf == 2) { $more = &$first.':'.&$second; }
$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];
}
您可以做的一件事是:
$ar = array(&$first, &$second);
$more = implode(":", $ar);
不是直接的,至少我不知道。 您可以使用自动组合值的方法创建一个类。如果只需要字符串输出,可以使用magic方法\uuuu 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
您可以通过以下方式获得所需的结果:
<?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];
}
您应该使用闭包来实现您想要的。事实上,您需要PHP7(可能是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
您是否尝试使用括号?@sakezz不起作用您试图通过连接引用来实现什么?在php中,这些与C中的指针不同。它们是符号表别名。你不能用它们做算术运算。这是一个可行的选择,但要小心,因为应用于此类数组的每个操作也将应用于引用的变量。不过,我个人认为使用function()(&$first,&$second)
比使用全局变量要好,因为全局变量可能会产生意外的副作用。是的,这一点不错。没有机会在PHP5.6下测试它,所以不想提出一个可能不起作用的答案。