0

I am getting the following error from the method presented below:

Notice: Uninitialized string offset: 5 in /path/to/file.php on line 30 Fatal error: Cannot access empty property in path/to/file.php on line 30

private function parse($xml, $index = '') {
    echo count($xml->children()); //outputs 6
    $count = 0;
    foreach ($xml->children() as $key => $value) {

        $this->$key[$count] = array();
        $count++;

    }

}

Any ideas why if I build an multi-dimensional in this way it results in an error?

If I change the assignment to:

$this->$key = array($count = > array());

This simply re-assigns the property each loop. Thanks Rich

2

2 Answers 2

1

Imagine you've got a string:

$string = 'abc`;

Doing substring access (which looks like array) will return you the character:

echo $string[2]; # c

Or you get your error when you're out of the index:

echo $string[3]; # null + warning

So now accessing a member of your object $this dynamically:

$this->$string[2]; # access $this->c

However this one breaks hardly:

$this->$string[3]; # access $this->null (not possible)

This gives you your fatal error of an empty property, a property with no name.

This explain what happens in your code, you have not told what you're trying to do so I hope this information will help you to continue with writing your parse function.

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

3 Comments

I see. So I am accessing a piece of the string, or trying to reassign a part of a string instead of assigning a new index.
You are actually first of all dynamically saying the name of the property. As the property results in no-name, you get the fatal error.
I am trying to dynamically build a multi-dimensional array. The xml has a handful of nodes named 'Class', which I'd like to set as an array $this->class[0], $this->class[1]... which has sub arrays. I want it dynamic because I have a few similarly structured XML files which I don't want to know all the names of each node. Thanks!
1

You should try to create the array before filling it. I.e. $this->key = array();

That is, before looping through the XML elements.

Comments

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.