QuestionsAlot
QuestionsAlot

Reputation: 3

PHP pass variable by reference using ?: operators

I have a problem when I try to call a function that expects a reference as parameter. The function works totally fine when I pass any variable to it, however if I pass a variable to it through the means of the ? and : if/else operators, I get the error Cannot pass parameter 1 by reference.

The function looks as following:

public function testFunction(&$var) {
    //It does nothing.
}

Now I'm attempting to call the function the following way:

$yes = 'yes';
$no = 'no';

$this->testFunction(
    TRUE ? $yes : $no
);

However if I do $this->testFunction($yes) it does work. What am I doing wrong here? Can I not use '?' and ':' for this, and if not what are my alternatives to make sure that testFunction will get a reference to the right data?

Upvotes: 0

Views: 35

Answers (1)

Mihai Matei
Mihai Matei

Reputation: 24276

That's because you are not passing the variable but its value instead. The expression si evaluated first and the passed argument is a string not a variable.

You can do it like this instead:

$yes = 'yes';
$no = 'no';

if (true) {
    $this->testFunction($yes);
} else {
    $this->testFunction($no);
}

Upvotes: 2

Related Questions