在类构造函数中返回 SimpleXML 对象 - 为什么它不起作用?
嘿,我设置了一个小测试用例,如下所示:
class T {
public function __construct(){
$obj = new SimpleXMLElement(file_get_contents('vote.xml'));
return $obj;
}
}
$vv=new T;
var_dump($vv);
$vv
的转储等于,在本例中,object(T)#1 (0) { }
-换句话说,不是预期的输出
当我在单独的函数中返回对象时,如下所示:
class T {
public function stackOverflow(){
$obj = new SimpleXMLElement(file_get_contents('vote.xml')); // or simplexml_load_file
return $obj;
}
}
$vv=new T;
$vv = $vv->stackOverflow();
var_dump($vv);
输出符合预期(包含“vote.xml”内容、标签和属性的对象) 。为什么我不能在构造函数中返回对象?谢谢!
Hey, I have a small test case set up as following:
class T {
public function __construct(){
$obj = new SimpleXMLElement(file_get_contents('vote.xml'));
return $obj;
}
}
$vv=new T;
var_dump($vv);
The dump of $vv
equals, in this case, object(T)#1 (0) { }
- in other words, not the expected output
When I return the object in a separate function, though, like this:
class T {
public function stackOverflow(){
$obj = new SimpleXMLElement(file_get_contents('vote.xml')); // or simplexml_load_file
return $obj;
}
}
$vv=new T;
$vv = $vv->stackOverflow();
var_dump($vv);
output is as expected (the object containing contents of 'vote.xml', tags and attributes). Why can I not return the object inside of the constructor? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
构造函数只会返回对新创建的对象的引用。这是有意为之的——否则你如何获得对新对象的引用呢?
但是,您可以在构造函数中创建一个对象属性,然后从外部访问它。这意味着您将在构造函数过程中创建对象,因此它将在正确的时间完成,而且可以保证完成。
当然,如果您不需要对新对象的引用,您可以使用静态方法而不使用构造函数:
The constructor will only ever return a reference to the newly created object. This is intentional -- how else would you get a reference to the new object?
You could, however, create an object property in your constructor and then access it from outside. This would mean that you would create the object during the constructor process, so it would be done at the right time and, what's more, could be guaranteed to be done.
Of course, if you don't need the reference to the new object, you could use a static method instead and never use the constructor: