Daniel A. White Daniel A. White - 16 days ago 6
PHP Question

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

Answer

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