开发者

Shorter notation for getting an object field

I'm 开发者_JAVA技巧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.


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.


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

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


You can do it only with functions/methods calls.
new is not a function, but a language construct.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜