Differences when instantiating a class

4

Using PHP when instantiating an object I do it as follows:

$obj = NEW my_class_exemplo;

however the auto complete of netbeans always gives me the option to put with parenthesis like this:

$obj = NEW my_class_exemplo();

Question: Is there any difference in the use of any of the options in terms of performance and mechanics?

    
asked by anonymous 22.01.2014 / 23:33

2 answers

5

In practice, there seems to be no difference.

As I understand it, most people and IDE implementations prefer to instantiate with parentheses to follow the code standard used in the PHP documentation itself and by the community in general, which follows that of other languages objects.

I did not find a reference in the PHP documentation, only one in the Wikipedia that says:

  

Function calls must have a parenthesis, except for the class constructor function when it has no arguments and is called with the new of PHP operator, where the parentheses are optional (free translation) .

Someone can argue that saving the two characters (2 bytes if using ASCII encoding, 4 if it's a UTF-8, ...) your PHP file would be loaded and interpreted faster. However, any gain is likely to be insignificant and unmeasurable, since PHP files are always full of "surplus" characters, especially when mixed with HTML.

    
23.01.2014 / 00:02
3

Actually using parentheses is optional when you do not inform the class constructor of data. The real need to report the parentheses is to pass data to the constructor. But for the sake of standardization always use with parentheses, as told to maintain a pattern.

<?php

class Foo {

    public function __construct() {
    }
}

class Bar {

    public function __construct( $data ) {

    }
}

new Foo; # Instancia correta, não acusará erro.
new Bar; # Instancia errada, acusará erro.
    
29.01.2014 / 03:55