Can I overload methods in PHP?

Example:

I want to have two different constructors, and I don't want to use func_get_arg (), because then it is invisible which arguments are possible.

Is it possible to write two of them, for example:

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

?

+3
source share
6 answers

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 take any number of arguments, and they need not be defined if you give them a default value. Here's how you can "fake" an overload function and allow access to functions with different arguments.

+10
source

PHP -, "" ( __call magic method), __call , , __get __set, " " / . , , .

( , , ), arity ( , ) .

+3

, .

+2

, , , .

if(count($args) == 0)
  $obj = new $className;
else {
 $r = new ReflectionClass($className);
 $obj = $r->newInstanceArgs($args);
}
+2

PHP ( varargs), , ( - varargs). , .

0
0

Source: https://habr.com/ru/post/1726973/


All Articles