1.2.144. Class-typed References

Class-typee arguments have no need for references. Since they are representing an object, they are already a reference.

In fact, adding the & on the argument definition may lead to error like Only variables should be passed by reference.

This applies to the object type hint, but not the the others, such as int or bool.

<?php
    // a class
    class X {
        public $a = 3;
    }

    // typehinted reference
    //function foo(object &$x) works too
    function foo(X &$x) {
        $x->a = 1;

        return $x;
    }

    // Send an object
    $y = foo(new X);

    // This prints 1;
    print $y->a;
?>

See also Passing by reference and Objects and references.

1.2.144.1. Suggestions

  • Remove reference for typehinted arguments, unless the typehint is a scalar typehint.

1.2.144.2. Specs

Short name

Functions/TypehintedReferences

Rulesets

All, Analyze, CE, CI-checks

Exakat since

1.2.8

PHP Version

All

Severity

Minor

Time To Fix

Instant (5 mins)

Precision

High

Features

reference

Available in

Entreprise Edition, Community Edition, Exakat Cloud