phpstringoopproperties

Get PHP class property by string


How do I get a property in a PHP based on a string? I'll call it magic. So what is magic?

$obj->Name = 'something';
$get = $obj->Name;

would be like...

magic($obj, 'Name', 'something');
$get = magic($obj, 'Name');

Solution

  • Like this

    <?php
    
    $prop = 'Name';
    
    echo $obj->$prop;
    

    Or, if you have control over the class, implement the ArrayAccess interface and just do this

    echo $obj['Name'];