Reputation: 2711
Is it somehow possible to "glue" two reference variables?
For example
$more = &$first.':'.&$second;
Using this, i receive a syntax error, an unexpected &.
Full code
$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];
}
Upvotes: 1
Views: 88
Reputation: 406
You should use a Closure to achieve what you want. Indeed, you need PHP 7(Maybe 5.6, can't tell as I can't test) in order to achieve desired result. Here's an example:
<?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
Upvotes: 1
Reputation: 1146
You can get your required result by:
<?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];
}
Upvotes: 0
Reputation: 3568
not directly, at least not that i know of. what you could do is create a class with a method that automatically combines the values. if you only want string output, you can use the magic method __tostring, so you can use the class directly:
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
Upvotes: 0
Reputation: 140
One thing you can do is the following :
$ar = array(&$first, &$second);
$more = implode(":", $ar);
Upvotes: 1