Shorter record to get an object field

I am wondering if there is a short notation in PHP for getting an object field when creating an object.

For example, in Java, I do not need to put the newly created object in a variable to get one of the fields. Example:

public class NewClass { public int testNum = 5; } 

now, to get the testNum field in the newly created object, all I have to do is:

int num = (new NewClass()).testNum;

Although a similar case in PHP would force me to do this:

 $obj = new NewClass(); $num = $obj->testNum; 

Is there a way in PHP to do this in one statement? Note. I can not edit classes.

+4
source share
3 answers

Perhaps you are looking for either static properties or constants

 public class NewClass { const NUM = 5; public static $num = 5; } $num = NewClass::NUM; $num = NewClass::$num; 

If you really need member members, then no, PHP does not currently support this, but it is planned for the next version 5.4.

+2
source

You can create a wrapper function in your class that calls the constructor, and you can simply:

 $num = NewClass::Create()->testNum; 
+2
source

You can only do this by calling functions / methods.
new is not a function, but a language construct.

+1
source

All Articles