1

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.

4
  • I am actually trying to figure out why your script doesn't exit when you call new LoadXML(). You haven't passed a parameter, yet you still call getNodes() in the constructor. In such a case, file_exists() would evaluate as false, causing the exit. Does your code shown here accurately reflect the entire class structure and the tests you are performing? Commented Dec 5, 2012 at 21:17
  • 2
    @MikeBrant his constructor gets never called. He has to rename it to __construct before your described behaviour will be correct in the second example. Commented Dec 5, 2012 at 21:24
  • @Benjamin Haha. I was spending my time looking at the actually logic that I didn'y actually look at the name of the method. Commented Dec 5, 2012 at 21:26
  • LoL! the simples things kill me ... :) Thanks Benjamin! Commented Dec 5, 2012 at 21:28

1 Answer 1

8

Try renaming your constructor to __construct

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir! Damn, I would have never thought of that. I would have expected php to give me an error or something ... Greatly appreciate your quick reply! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.