Differences when instantiating a class

Asked

Viewed 1,232 times

4

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

$obj = NEW my_class_exemplo;

but always the netbeans auto complete gives me the option to put parentheses like this:

$obj = NEW my_class_exemplo();

Question: There is some difference in the use of some of the options in terms of performance and mechanics?

2 answers

6


In practice, there seems to be no difference.

From what I understand, most people and IDE implementations prefer to instantiate in parentheses to follow the standard code used in PHP’s own documentation and by the wider community, which follows that of other object-oriented languages.

I couldn’t find a reference in the PHP documentation, just one in Wikipedia what it says:

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

One might argue that by saving the two characters (2 bytes if using ASCII encoding, 4 if it is a UTF-8, ...) your PHP file would be loaded and interpreted faster. However, any gain will probably be insignificant and not measurable, since PHP files are always full of "leftover" characters, especially when mixed with HTML.

5

In reality the use or not of the parentheses is optional when you do not inform data to the class constructor. The real need to inform the parentheses is to pass data to the constructor. But for the sake of standardization always use with parentheses, as said to maintain a standard.

<?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.

Browser other questions tagged

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