atoms atoms - 4 days ago 5
PHP Question

Retreiving PHP property name as string

I have some JSON, if I

var_dump
the output looks like:

var_dump( $oJSON->{$oQ->sQuestionName} );

object(stdClass)[14]
public 'Lease' => boolean true


I would like to retrieve 'Lease' as a string.

I've tried casting it:

(string)$oJSON->{$oQ->sQuestionName}


but it returns an
E_RECOVERABLE
:

E_RECOVERABLE_ERROR Error: Object of class stdClass could not be converted to string


The following works, however I feel there must be a better way?

array_shift(array_values(array_keys(get_object_vars($oJSON->{$oQ->sQuestionName}))));


N.B. I can't use to use the following due to compatability issues

array_keys(get_object_vars($oJSON->{$oQ->sQuestionName}))[0]


Any ideas?

Answer

Use ReflectionClass::getProperties() to get a list of the object's properties.

$reflect = new ReflectionClass($foo);
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);
Comments