Can I overload methods in PHP?

后端 未结 6 1920
隐瞒了意图╮
隐瞒了意图╮ 2021-01-06 20:01

Example:

I want to have two different constructors, and I don\'t want to use func_get_arg(), because then it\'s invisible what args are possible.

Is it legal

6条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-06 20:17

    No, but you can do this:

    class MyClass {
        public function __construct($arg = null) {
            if(is_array($arg)) {
                // do something with the array
            } else {
                // do something else
            }
        }
    }
    

    In PHP, a function can receive any number of arguments, and they don't have to be defined if you give them a default value. This is how you can 'fake' function overloading and allow access to functions with different arguments.

提交回复
热议问题