Search code examples
phpoopnotation

Shorter notation for getting an object field


I'm wondering if there's a short notation in PHP for getting an object field when creating an object.

For example, in Java, I don't have to put a newly created object in a variable in order to get one of it's fields. Example:

public class NewClass {
    public int testNum = 5;
}

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

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

While 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 it in one statement? Note: I cannot edit the classes.


Solution

  • Maybe 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 are really need object members, then no, PHP currently doesn't support this, but its scheduled for the next 5.4 release.