How to add methods dynamically

后端 未结 8 1485
故里飘歌
故里飘歌 2021-01-01 15:15

I\'m trying to add methods dynamically from external files. Right now I have __call method in my class so when i call the method I want, __call inc

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-01 16:07

    /**
     * @method Talk hello(string $name)
     * @method Talk goodbye(string $name)
     */
    class Talk {
        private $methods = [];
        
        public function __construct(array $methods) {
            $this->methods = $methods;
        }
        
        public function __call(string $method, array $arguments): Talk {
            if ($func = $this->methods[$method] ?? false) {
                $func(...$arguments);
                
                return $this;
            }
            
            throw new \RuntimeException(sprintf('Missing %s method.'));
        }
    }
    
    $howdy = new Talk([
        'hello' => function(string $name) {
            echo sprintf('Hello %s!%s', $name, PHP_EOL);
        },
        'goodbye' => function(string $name) {
            echo sprintf('Goodbye %s!%s', $name, PHP_EOL);
        },
    ]);
    
    $howdy
        ->hello('Jim')
        ->goodbye('Joe');
    

    https://3v4l.org/iIhph

提交回复
热议问题