Can I overload methods in PHP?

2019-02-15 04:33发布

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 to write two of them, like:

class MyClass {
    public function __construct() {
    // do something
    }
    public function __construct(array $arg) {
    // do something
    }
}

?

标签: php oop
6条回答
We Are One
2楼-- · 2019-02-15 05:15

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.

查看更多
Anthone
3楼-- · 2019-02-15 05:20

Nope, you can't do that.

查看更多
在下西门庆
4楼-- · 2019-02-15 05:23

Since the PHP is a weak-typing language and it supports functions with variable number of the arguments (so-called varargs) there is no difference to processor between two functions with the same name even they have different number of declared arguments (all functions are varargs). So, the overloading is illegal by design.

查看更多
小情绪 Triste *
5楼-- · 2019-02-15 05:23

You can also use func_get_args() to create pseudo-overloaded functions, though that may cause a confusing interface for your method/function.

查看更多
霸刀☆藐视天下
6楼-- · 2019-02-15 05:27

This is not possible, however to solve the problem of invisible args, you can use the reflection class.

if(count($args) == 0)
  $obj = new $className;
else {
 $r = new ReflectionClass($className);
 $obj = $r->newInstanceArgs($args);
}
查看更多
Root(大扎)
7楼-- · 2019-02-15 05:38

PHP has something that it calls "overloading" (via the __call magic method), but what really happens is the magic method __call is invoked when an inaccessible or non-existent method, rather like __get and __set let you "access" inaccessible/non-existent properties. You could use this to implement overloading of non-magic methods, but it's unwieldy.

As formal parameters can be untyped (which is distinct from the argument values being untyped, since those are typed) and even function arity isn't strictly enforced (each function has a minimum number of arguments, but no theoretical maximum), you could also write the method body to handle different number and types of arguments.

查看更多
登录 后发表回答