Builders in PHP 7

2

I was testing a class in PHP 7, and noticed that the constructor no longer works when it is created from the class name, only working when it is created with the name __construct .

Example:

<?php

// Assim funciona:
class MinhaClasse {
    public function __construct() {
        echo 'Ok!';
    }
}

// Assim não:
class MinhaClasse {
    public function MinhaClasse() {
        echo 'Ok!';
    }
}

Has there been any change? And if so, why?

    
asked by anonymous 31.03.2018 / 02:52

2 answers

4

I could not state the reason for the change, I can say a few things I know about PHP that can give clues.

We all know, and some do not accept, that the PHP development process is chaotic, usually done by programmers up to good, but who do not know how to create a language. It does not help the fact that PHP has already been created in a way without much understanding of how a language works .

I think one day someone thought it would be better to have a neutral-named method because if you rename the class, you would save typing to change the constructor, then you would change the original form that was good and did not create problems for anyone in a new way which only brought a punctual and questionable advantage.

In fact it seems to me a very wrong motive. You should not rename your classes, this causes a lot of impact on a large system. And if you rename, the least of your problems will also be to rename the constructor within the class (you will have to rename it in every application that calls this class).

It may not be so difficult to change everything in the application. But if this is true, why are you using OOP? In simple things OOP has no advantages, so none of this should be discussed.

PHP has other shortcomings that hinder the development of large applications that are in need of OOP.

It is also said that it would be to use the class name as a common method. I do not know what advantage this gives. I know it causes confusion because the constructor will be called with the class name, so it would have common constructor and method with the same name. Just lick it.

    
31.03.2018 / 04:14
5

This was a change that happened in PHP 7.
You can read about this in documentation .

Has there been any change?

According to the documentation cited above:

  

Old-style builders have become OBSOLETE in PHP 7.0, and will be removed in a future release.

If so, why?

The documentation does not mention this explicitly, but there is a snippet of code:

<?php
namespace Foo;
class Bar {
    public function Bar() {
        // tratado como construtor no PHP 5.3.0-5.3.2
        // tratado como método comum a partir do PHP 5.3.3
    }
}

Which indicates that the reason for such a change was likely to be the ability to create common methods with the class name, which was not possible when the variables were defined from the class name.

    
31.03.2018 / 03:01