Constructor overloading in PHP

Method overloading is a partial case of polimorphism. With method overloading we can define different methods with the same name, and these methods can vary on type and a number of arguments. This is especially useful for class constructors. But PHP is a weak-type language and it does not allow several constructors in a class. How we can use method overloading in PHP even it is not a strong-type language?

Say we have a Student class and we want to create Student-instances based on student’s name, or student’s ID, e-mail, or maybe mobile phone number. We could have just one __construct() in the Student class and use a cascading IF THEN statements there to check to arguments. But this is an ugly solution. It would difficult to both test and extend it.

There is much better solution to the problem – overloading. We can use a couple of statical fabric-helpers methods with different arguments, that will create Student-instances for us. The original constructor can even be a private or protected.

class Student
{
    protected $firstName;
    protected $lastName;
    protected $id;

    protected function __construct()
    {}

    static function createWithName($firstName, $lastName)
    {
        $instance = new self();
        $instance->setName($firstName, $lastName);
        return $instance;
    }

    static function createWithID($id)
    {
        $instance = new self();
        $instance->setId($id);
        return $instance;
    }

    //static function createWithPhone($phoneNumber)
     //static function createWithEmail($email)

    protected function setId($id)
    {
        $this->id = $id;
    }

    protected function setName($firstName, $lastName)
    {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
    }
}

$student1 = Student::createWithID(10);
$student2 = Student::createWithName("Petr", "Sidorov");