PHP function overloading

前端 未结 10 1000
北恋
北恋 2020-11-22 17:24

Coming from C++ background ;)
How can I overload PHP functions?

One function definition if there are any arguments, and another if there are no arguments? Is it

10条回答
  •  猫巷女王i
    2020-11-22 17:31

    PHP doesn't support traditional method overloading, however one way you might be able to achieve what you want, would be to make use of the __call magic method:

    class MyClass {
        public function __call($name, $args) {
    
            switch ($name) {
                case 'funcOne':
                    switch (count($args)) {
                        case 1:
                            return call_user_func_array(array($this, 'funcOneWithOneArg'), $args);
                        case 3:
                            return call_user_func_array(array($this, 'funcOneWithThreeArgs'), $args);
                     }
                case 'anotherFunc':
                    switch (count($args)) {
                        case 0:
                            return $this->anotherFuncWithNoArgs();
                        case 5:
                            return call_user_func_array(array($this, 'anotherFuncWithMoreArgs'), $args);
                    }
            }
        }
    
        protected function funcOneWithOneArg($a) {
    
        }
    
        protected function funcOneWithThreeArgs($a, $b, $c) {
    
        }
    
        protected function anotherFuncWithNoArgs() {
    
        }
    
        protected function anotherFuncWithMoreArgs($a, $b, $c, $d, $e) {
    
        }
    
    }
    

提交回复
热议问题