Bonjour à tous,

Si on prend un object quelconque ont peut accèder à une de ses propriété en varaible ne faisant :

$une_propriété = 'nom';
$mon_objet->$une_propriété = $une_valeur

Mon problème est que je souhaite accéder à une propriété d'un sous objet, style :

$une_propriété = 'sous_objet->propriété';
$mon_objet->$une_propriété = $une_valeur

Dans le second cas, cela ne marche, y a t il une notation différente ou un autre moyen ?

Merci

2 réponses


tleb
Réponse acceptée

J'aime pas donner du code tout fait, mais je me suis fait plaisir sur cette fonction (à mettre dans un namespace/objet/autre, en fonction de ton besoin/setup/framework).

function getNestedProperty($object, $properties, $separator = '->')
{
    if (is_string($properties)) {
        $properties = explode((string) $separator, $properties);
    } elseif (!is_array($properties)) {
        throw new Exception(
            'The properties argument must be a string or an array.'
        );
    }

    if (!is_object($object)) {
        throw new Exception(
            'The object argument must be an object.'
        );
    }

    $res = $object;

    foreach ($properties as $key => $value) {

        if (!property_exists($res, $value)) {
            throw new Exception(sprintf(
                'The "%s" property does not exist in the "%s" object.',
                $value,
                get_class($res)
            ));
        }

        $res = $res->$value;
    }

    return $res;
}

class Foo { public $bar; }
class Bar { public $baz; }
class Baz {}

$baz = new Baz;
$bar = new Bar;
$bar->baz = $baz;
$foo = new Foo;
$foo->bar = $bar;
$properties = 'bar->baz';

var_dump(getNestedProperty($foo, $properties)); // => instance de Bar

Pas de formule magique :(

J'en été arrivé a peu près à la même conclusion que ton code, merci.