用于获取对象字段的更短表示法
我想知道 PHP 中是否有一个简短的符号用于在创建对象时获取对象字段。
例如,在 Java 中,我不必将新创建的对象放入变量中即可获取其字段之一。 示例:
public class NewClass {
public int testNum = 5;
}
我所要做的就是:
int num = (new NewClass()).testNum;
现在,要获取新创建的对象中的 testNum
字段, PHP 中的 case 会迫使我这样做:
$obj = new NewClass();
$num = $obj->testNum;
Is there a way in PHP to do it in one statements? 注意:我无法编辑课程。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许您正在寻找静态属性或常量,
如果您确实需要对象成员,那么不,PHP 目前不支持此功能,但计划在下一个 5.4 版本中发布。
Maybe you are looking for either static properties, or constants
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:
您只能通过函数/方法调用来完成此操作。
new
不是一个函数,而是一个语言结构。You can do it only with functions/methods calls.
new
is not a function, but a language construct.