dongqing5925 2012-12-05 21:08
浏览 80
已采纳

PHP从构造函数中调用类方法而不填充数组

I have a very weird problem that when I call the method of a class from within the constructor I get as a result empty arrays, but when I call the method from the class instance it works fine.

Here is the code for loadxml.php:

include('XMLNode.php'); // this is a simple object class

class LoadXML
{
public $MyNodes = array();

public function __constructor($xmlFile)
{
    $this->getNodes($xmlFile);
}

public function getNodes($xmlFile)
{
    if (file_exists($xmlFile)) {
        $xmlNodes = simplexml_load_file($xmlFile);

        foreach ($xmlNodes->XMLNode as $key => $value) {
            array_push($this->MyNodes, $value);
        }
    }
    else
    {
        exit('Failed to open xml file '.$xmlFile);
    }
}
}

Now in the main file if I make the call like this:

include('loadxml.php');

$nodes = new LoadXML('myXMLFile.xml');

print "<pre>";
print_r($nodes);
print "</pre>";

... the result looks like this:

LoadXML Object ( [MyNodes] => Array ( ) )

If I make the call from the class instance like this and comment out the call to getNodes from the LoadXML constructor:

include('loadxml.php');

$nodes = new LoadXML();
$nodes->getNodes('myXMLFile.xml');

print "<pre>";
print_r($nodes);
print "</pre>";

I will get the correct output. What's happening? What am I doing wrong in the first approach? Am I missing something from the class constructor? I looked in the manual (http://php.net/manual/en/oop4.newref.php) and the call to the method seems legit from within the constructor.

  • 写回答

1条回答 默认 最新

  • duanshang9426 2012-12-05 21:12
    关注

    Try renaming your constructor to __construct

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题