2

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 myclass(123); //> call the first construct
new myclass(123,'abc'); //> call the second
5
  • duplicate of stackoverflow.com/questions/1985182/… Commented Mar 11, 2011 at 10:43
  • 2
    Current stable version is 5.3.5, are you asking about latest development snapshots? Commented Mar 11, 2011 at 10:44
  • @alvaro: what's the difference? Commented Mar 11, 2011 at 10:45
  • with PHP 5.3.7 not being released yet, the only correct answer is: we cannot know. But since current versions of PHP do not support this, it is unlikely that any PHP 5.3.7 will. Commented Mar 11, 2011 at 10:58
  • PHP/5.3.7 does not exist. If you are asking whether you can do it now, the question is already answered (see @bazmegakapa's link). If you are asking whether PHP is planning overloading for future releases, the question is entirely different. Commented Mar 11, 2011 at 11:12

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

0

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);
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.