开发者

Overloading construct in php?

does php (5.3.7) supports overloading ?

Example:

class myclass{

function __construct($arg1) { // Construct with 1 param}
function __construct($arg1,$arg2) { // Construct with 2 param}

}


new myc开发者_开发百科lass(123); //> call the first construct
new myclass(123,'abc'); //> call the second


You have to implement the constructor once and use func_get_args and func_num_args like this:

<?php

class myclass {
    function __construct() {
        $args = func_get_args();

        switch (func_num_args()) {
            case 1:
                var_dump($args[0]);
                break;
            case 2:
                var_dump($args[0], $args[1]);
                break;
            default:
                throw new Exception("Wrong number of arguments passed to the constructor of myclass");
        }
    }
}

new myclass(123); //> call the first construct
new myclass(123,'abc'); //> call the second
new myclass(123,'abc','xyz'); //> will throw an exception

This way you can support any number of arguments.


No, but it supports optional parameters, or variable number of parameters.

class myclass{
  function __construct($arg1, $arg2 = null){
    if($arg2 === null){ // construct with 1 param //}
    else{ // construct with 2 param //}
  }
}

Note that this has the downside that if you actually want to be able to supply null as a second parameter it will not accept it. But in the remote case you want that you can always use the func_* family of utils.


I would define some fromXXX methods that call the __constructor which takes a parameter like id.

<?php
class MyClass {
   public function __construct(int $id) {
       $instance = Database::getByID($id);
       $this->foo = $instance['foo'];
       $this->bar = $instance['bar'];
   }
   public static function fromFoo(string $foo): MyClass {
       $id = Database::find('foo', $foo);
       return new MyClass($id);
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜