Is it possible to declare a method static and nonstatic in PHP?

后端 未结 5 1468
北荒
北荒 2020-12-01 09:04

Can I declare a method in an object as both a static and non-static method with the same name that calls the static method?

I want to create a class that has a stati

5条回答
  •  佛祖请我去吃肉
    2020-12-01 09:18

    I would make a hidden class as the constructor and return that hidden class inside the parent class that has static methods equal to the hidden class methods:

    // Parent class
    
    class Hook {
    
        protected static $hooks = [];
    
        public function __construct() {
            return new __Hook();
        }
    
        public static function on($event, $fn) {
            self::$hooks[$event][] = $fn;
        }
    
    }
    
    
    // Hidden class
    
    class __Hook {
    
        protected $hooks = [];
    
        public function on($event, $fn) {
            $this->hooks[$event][] = $fn;
        }
    
    }
    

    To call it statically:

    Hook::on("click", function() {});
    

    To call it dynamically:

    $hook = new Hook;
    $hook->on("click", function() {});
    

提交回复
热议问题