Class with more than one __constructor in PHP?

Asked

Viewed 561 times

3

I was here studying a little more about builders in PHP. And I ran into some questions.

1 - It is possible for a class to have more than one constructor?

2 - If yes, how to know which one will be started?

  • 2

    If I’m not mistaken, php does not have native overloading, but there are ways to "simulate" it.

  • Here shows an "alternative" way of simulating overloading.

1 answer

2


In theory it is not possible for a class to have more than one constructor in PHP. Because it is a dynamic language, overloading of methods does not house very well.

What exists in PHP are two ways to create a constructor. One in the form of the "magic method" __construct and another that was introduced at the very beginning of 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 there is no __construct in class.

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

  • I’m not sure if he wants to extend classes, but the question to understand something similar to this http://answall.com/q/37563/3635seems to me a duplicate

  • Related: http://answall.com/q/123459/101

Browser other questions tagged

You are not signed in. Login or sign up in order to post.