Cannot create reference to property %s::$%s

Description

While it is possible to acquire a reference on an object’s property, it is not possible to acquire that reference on a property with hooks. By default, the property hook is returned by value, and cannot accomodate the reference. Unless the property hooks is made by reference, with a & before the name of the hook.

The message is also related to using an object in a foreach loop. There is a different message for direct creation of a reference on a property.

Example

<?php

class X {
    public $byRef {
        get {
            $x = 42;
            return $x;
        }
    }
}

foreach (new X as $prop => &$value) {
    var_dump($value);
}

?>

Solutions

  • Add & before the get hook.

  • Make the property a normal property, without hooks.

  • Avoid using a reference on a property hook.