oop - Overloading construct in php?

929

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
997

Answer

Solution:

You have to implement the constructor once and usefunc_get_args andfunc_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.

935

Answer

Solution:

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 supplynull as a second parameter it will not accept it. But in the remote case you want that you can always use thefunc_* family of utils.

41

Answer

Solution:

I would define somefromXXX methods that call the__constructor which takes a parameter likeid.

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

People are also looking for solutions to the problem: php - Sort an array of objects by fields

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.