Get PHP class property by string

Daniel A. White picture Daniel A. White · Apr 30, 2009 · Viewed 124.6k times · Source

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');

Answer

Peter Bailey picture Peter Bailey · Apr 30, 2009

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'];