4

Reproduced with this code

<?php
$justReturn1 = function() { return 1;};

class A {
        public $f;
        public function __construct($func) {
                $this->f = $func;
        }
}

$instance = new A($justReturn1); // Create instance

$f = $instance->f; // Assign the function within $instance->f to a variable external to object

echo $f(); // Returns: 1
echo $instance->f(); // Returns: Fatal error: Call to undefined method A::f()

The same function can be invoked if I assign it to a variable, but can't be invoked if I assign it to an object property.

This is really annoying, since I was counting on this consistency (common sense).

I'm writing a class that receives a big configuration array with some validation functions inside it. I then store those validation functions on an object just fine, but I need an indirection step (creating a variable and assigning this function to it) before I can invoke them!

Is there a flaw in my test? Is this actually PHP unimplementedness?

mlg
  • 1,447
  • 15
  • 19
  • It's possible with `call_user_func($instance->f)` or defining `__call()`: http://stackoverflow.com/questions/4535330/calling-closure-assigned-to-object-property-directly I had to dig a little to come up with a comparable question, but I figured we must have had one. It's an interesting problem and use case. – Michael Berkowski Feb 01 '15 at 20:23
  • Whoops. Thanks for pointing out the duplication. I still think there's value in the question existing; after all, I couldn't find this other question myself. – mlg Feb 01 '15 at 23:13
  • 1
    Linking it as a duplicate won't cause it to be removed - rather it will remain as a signpost to the existing one. The other wasn't easy to find, and yours will make it a little easier – Michael Berkowski Feb 01 '15 at 23:25

0 Answers0