Storing a Closure Function in a Class Property in PHP

后端 未结 6 1024
清歌不尽
清歌不尽 2021-01-21 07:37

ok I do have the code below

bar();
       }
    }

    $mee         


        
6条回答
  •  -上瘾入骨i
    2021-01-21 08:03

    You need to exploit some magic functionality of PHP (__call) to make use of that. Extend from Extendable for example:

    class Extendable {
        static function import($context) {
            $self = new static();
            while (is_callable($context)) $context = $context($self);
            if (is_array($context) || is_object($context) || is_a($context, 'Traversable')) {
                foreach($context as $key => $value)
                    $self->$key = &$value; # preserve keys if
            }
            return $self;
        }
        public function __call($name, $args) {
            if (isset($this->$name) && is_callable($this->$name)) {
                return call_user_func_array($this->$name, $args);
            }
            throw new BadFunctionCallException(sprintf('Undefined function %s.', $name));
        }
    }
    

    And you can do the job. It's not that nice. Background and examples are in one of my blog posts:

    • PHP: Extending stdClass with Closures (plus Visitor)

    You can naturally implement that magic functionality your own, too.

提交回复
热议问题