Class with more than one

2

I was here studying a bit more about builders in PHP . And I came across some doubts.

1 - Is it possible for a class to have more than one constructor?

2 - If so, how do you know which one will be started?

    
asked by anonymous 14.06.2016 / 02:21

1 answer

1

In theory it is not possible for a class to have more than one constructor in PHP. Because it is a dynamic language the overloading methods do not home very well.

What's in PHP are two ways to build a builder. One in the form of the "magic method" __construct and another that was introduced early in the Object Orientation in PHP 4, where the constructor was the method with the same class name.

Example:

<?php

class ExampleA {

    public function __construct(){
        echo 'Método Mágico' . PHP_EOL;
    }

    public function ExampleA(){
        echo 'Construtor descontinuado';
    }

}

class ExampleB {

    public function ExampleB(){
        echo 'Construtor descontinuado' . PHP_EOL;
    }

}


$eA = new ExampleA;  // Retorna 'Método Mágico'
$eB = new ExampleB;  // Retorna 'Construtor descontinuado'

As you can see in this example in 3v4l , PHP will give priority to __construct and will only execute the method with the same name if it does not exist a __construct in the class.

Remember that the second form was discontinued in PHP 7 (being warned in the form of a warning ) and will be removed in the future. So, use the conventional form ( __construct ) to avoid problems in the future.

    
14.06.2016 / 02:34