Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReflectionObject vs. cast to array vs. get_object_vars for retrieving public vars

Tags:

php

I need to get the public properties of an object; is there a preferred method for doing this? I'm wary of using ReflectionObject#getProperties() because of the Reflection API overhead, but between casting the object to an array and using get_object_vars(), is there an established standard or clear performance gain for one or the other?

To be clear, I realize that casting the object to an array will give me all the object's properties, but as protected properties will be prepended with * and private properties will be prepended with the class name, it would still be effective for a quick in_array($property, $properties); call.

like image 687
Derek Stobbe Avatar asked Sep 12 '11 16:09

Derek Stobbe


2 Answers

As you want to get the public properties of the object, you should definitely use get_object_vars, which is a function specifically designed for that task, instead of using some obscure (array) cast with unclear behavior.

like image 149
NikiC Avatar answered Oct 14 '22 06:10

NikiC


It depends, they don't do the same thing.

get_object_vars() will return only the variable that are visible from the calling scope (e.g. it may or may not return protected or private variable).

Casting to array returns all properties, including private ones.

like image 27
Arnaud Le Blanc Avatar answered Oct 14 '22 06:10

Arnaud Le Blanc