Home » Php » php – Only variables should be passed by reference

php – Only variables should be passed by reference

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have a class:

class Validator {
    private $validationArray;
    private $cleanedValues;

    public function __construct($arg1, $arg2=NULL) {
        if(empty($arg2)) {
            $this->LoadValidatorByName($arg1);
        } else {
            $this->LoadValidatorFromLeadType($arg1, $arg2);
        }
    }

    private function LoadValidatorFromLeadType($lead_type, $vocabulary) {
            $ErrorReporter = new ErrorReporter;
            $taxonomy_term = reset(taxonomy_get_term_by_name($lead_type, $vocabulary));

...some more stuff

The function taxonomy_get_term_by_name is a Drupal function but the issue I am experiencing is a PHP one.

When this method is called PHP complains with:

Strict warning: Only variables should be passed by reference in Validator->LoadValidatorFromLeadType() (line 32 of [path to my file])

Line 32 is ths line with:

$taxonomy_term = reset(taxonomy_get_term_by_name($lead_type, $vocabulary));

I’ve looked in to the error and I’m pretty sure I know what it means, but I can’t understand what is wrong with my code that causes this warning.

How to&Answers:

reset is waiting for a variable reference. You are passing it a function result…

$taxonomy_term = taxonomy_get_term_by_name($lead_type, $vocabulary);
$taxonomy_term = reset($taxonomy_term );

Answer:

This mean that only variable should be passed by reference, not an expression.

reset($array_variable); // correct

and

reset(some_function_that_returns_array()); // incorrect

If you take a second and think about it more – you would find that reset() with expression (not a variable) makes no sense, because you’ve rewind the array pointer to the beginning, but you don’t have the ability to access that array anymore.

Answer:

You should only reset a variable (which is passed by reference), not a return value of a function.
see: http://www.php.net/reset