Wojciech Szabowicz
Wojciech Szabowicz

Reputation: 4198

Dynamic object properties

I've got a question, is it possible to add dynamical properties to object like

private function get_invoice_info($data, array $rel)
{
    foreach ($data as $info)
    {
        foreach($rel as $val)
        {
           $info->$val->$val->etc;
        }
    }

    return $value;
}

Problem is that object properties can be an object and has it own properties or relations.

Like $info->contract and $info->contract->contractor.

Upvotes: 0

Views: 86

Answers (1)

deceze
deceze

Reputation: 522024

If the objects don't exist yet, you need to create them:

$info->$foo = new stdClass;
$info->$foo->$bar = new stdClass;
$info->$foo->$bar->$baz = 42;

But I don't see the point in doing this over simply using arrays. stdClass objects don't really give you any advantage and arrays can be created implicitly to an unlimited depth:

$info[$foo][$bar][$baz] = 42;

Upvotes: 1

Related Questions