What is the correct option for instantiating a class in PHP?


What is the correct option for instantiating a class in PHP?

Whereas the class is under discussion if you call Atleta :




$atleta= new Atleta();


$atleta= Atleta();

Which of the 3 options is the correct way to instantiate a class in PHP?

asked by FELIPE GARCIA DO AMARAL 09.11.2016 в 12:11

3 answers


In the context of the question would be the 2nd option:

$atleta = new Atleta();

But remember that in PHP, it is not necessary to use () parenthesis when the class has no constructor or the constructor does not need arguments.

So, that would also be true:

$atleta = new Atleta;

Explanation of each option

I do not know if I'm wrong, but the question looks very much like an evaluative question. So assuming this, I do not think it's cool just to "give the right answer," but to explain what each thing does.


$atleta = Atleta;

Generally, this syntax is used in PHP to get the value of a constant.

For example:

const Atleta = 'Atleta';

// ou 

define('Atleta', 'Atleta');

$atleta = Atleta;

Note : When attempting to assign the value of an undefined constant, you will receive an error message of type E_NOTICE and the value assigned will be a string as the name of the nonexistent constant. >


$atleta= Atleta();

This syntax above is used for the direct call of functions. Functions in PHP are called using the parenthesis, and you can pass arguments or not.


 function Atleta() {
       return 'Atleta';

$atleta = Atleta();
09.11.2016 в 13:47

You use option 2, like this:

$atleta= new Atleta();

You can read more here php.net

09.11.2016 в 12:19

According to the official PHP website, you should use the new statement to instantiate a class.

If you instantiate an empty generic object the best way is to use the method below:

$obj = new obj(); 

Being the most correct and fast way.

09.11.2016 в 14:07