cyberfly
2/7/2018 - 5:49 AM

PHP Object nested variable variable

<?php

    //access object property using variable variable

    function accessProperty($object, $path)
    {
        $exploded_path = explode("->", $path);
        $prop = $object;
        foreach ($exploded_path as $p) {
            if (isset($prop->$p)) {
                $prop = $prop->$p;
            }
            else {
                $prop = null;
                break;
            }

        }

        return $prop;
    }
    
    //example usage
    
    $property = 'links->first->name';
    
    accessProperty($object, $property);