Tomasz Gałkowski
Tomasz Gałkowski

Reputation: 1929

Why is this variable variable not acting properly? PHP

I have this foreach loop.

$i2 looks like this (everytime):

$i2 = array(
    'id' => "category['id']"
);

And here is a foreach loop.

foreach ($i2 as $o3 => $i3)
{
    if (is_array($i3) !== true)
        {
            $new .= "<{$o3}>{$node->$i3}</{$o3}>";
        } else {
            $new .= "<{$o3}>";
            $new .= "</{$o3}>";
        }
    }
}

$node is a new SimpleXMLElement($xml_reader->readOuterXML());. But this is working properly.

The problem is here: if I use $node->$i3 in order to get XML value of that field - it doesn't work. But if I substitute it for $node->category['id'] it does. Which seems weird as $i3 contains category['id'] and I can check that with debug tools.

I was using this in the previous projects and variable of variable was working fine. Now it doesn't. Why?

@edit

This is what happens before the code:

// i move the cursor to the first product tag
while ($xml_reader->read() and $xml_reader->name !== 'product');

        // i iterate over it as long as I am inside of it
        while ($xml_reader->name === 'product')
        {

            // i use SimpleXML inside XMLReader to work with nodes easily but without the need of loading the whole file to memory
            $node = new SimpleXMLElement($xml_reader->readOuterXML());

            foreach ($this->columns as $out => $in)     // for each XML tag inside the product tag
        {
            // ... do stuff

Basically this is what happens before the code in question. The $columns is an array that enables the configuration of input XML file (keys are Prestashops XML tags and values are names of tags in the user's XML file).

For example:

<product>
    <associations>
         <categories>
             <category>
                 <id></id>
             </category>
         <category>
    </associations>
</products>

And in input one:

<category id="1"></category>

So in $columns:

$columns = ('associations' => array(
    'categories' => array(
        'category' => 'category['id'] // this is what $i3 later is
    )
));

I can get to the given point of XML file easily. I get the category['id'] value and this is what $i3 is.

Upvotes: 2

Views: 77

Answers (1)

Amarnasan
Amarnasan

Reputation: 15579

The PHP preprocessor tries to find the $i3 property on $node. But the object $node has no such property, and then it fails.

Are you sure you use the same syntax when trying to reach the category['id'] property in your previous projects?

You can try this syntax:

foreach ($i2 as $o3 => $i3)
{
    if (is_array($i3) !== true)
    {
        $new .= "<{$o3}>" . eval("return \$node->$i3;") ."</{$o3}>";
    } else {
        $new .= "<{$o3}>";
        $new .= "</{$o3}>";
    }
}

Upvotes: 2

Related Questions