|
|
 |
get_object_vars (PHP 4, PHP 5) get_object_vars -- Returns an associative array of object properties Descriptionarray get_object_vars ( object obj )
This function returns an associative array of defined object properties
for the specified object obj.
Note:
In versions prior to PHP 4.2.0, if the variables declared in the class
of which the obj is an instance, have not been
assigned a value, those will not be returned in the array. In versions
after PHP 4.2.0, the key will be assigned with a NULL value.
Example 1. Use of get_object_vars() |
<?php
class Point2D {
var $x, $y;
var $label;
function Point2D($x, $y)
{
$this->x = $x;
$this->y = $y;
}
function setLabel($label)
{
$this->label = $label;
}
function getPoint()
{
return array("x" => $this->x,
"y" => $this->y,
"label" => $this->label);
}
}
$p1 = new Point2D(1.233, 3.445);
print_r(get_object_vars($p1));
$p1->setLabel("point #1");
print_r(get_object_vars($p1));
?>
|
The above example will output: Array
(
[x] => 1.233
[y] => 3.445
[label] =>
)
Array
(
[x] => 1.233
[y] => 3.445
[label] => point #1
) |
|
See also get_class_methods() and
get_class_vars().
User Contributed Notes
get_object_vars
fmmarzoa at librexpresion dot org
02-Nov-2004 01:53
You can still cast the object to an array to get all its members and see its visibility. Example:
<?php
class Potatoe {
public $skin;
protected $meat;
private $roots;
function __construct ( $s, $m, $r ) {
$this->skin = $s;
$this->meat = $m;
$this->roots = $r;
}
}
$Obj = new Potatoe ( 1, 2, 3 );
echo "<pre>\n";
echo "Using get_object_vars:\n";
$vars = get_object_vars ( $Obj );
print_r ( $vars );
echo "\n\nUsing array cast:\n";
$Arr = (array)$Obj;
print_r ( $Arr );
?>
This will returns:
Using get_object_vars:
Array
(
[skin] => 1
)
Using array cast:
Array
(
[skin] => 1
[ * meat] => 2
[ Potatoe roots] => 3
)
As you can see, you can obtain the visibility for each member from this cast. That which seems to be spaces into array keys are '\0' characters, so the general rule to parse keys seems to be:
Public members: member_name
Protected memebers: \0*\0member_name
Private members: \0Class_name\0member_name
I've wroten a obj2array function that creates entries without visibility for each key, so you can handle them into the array as it were within the object:
<?php
function obj2array ( &$Instance ) {
$clone = (array) $Instance;
$rtn = array ();
$rtn['___SOURCE_KEYS_'] = $clone;
while ( list ($key, $value) = each ($clone) ) {
$aux = explode ("\0", $key);
$newkey = $aux[count($aux)-1];
$rtn[$newkey] = &$rtn['___SOURCE_KEYS_'][$key];
}
return $rtn;
}
?>
I've created also a <i>bless</i> function that works similar to Perl's bless, so you can further recast the array converting it in an object of an specific class:
<?php
function bless ( &$Instance, $Class ) {
if ( ! (is_array ($Instance) ) ) {
return NULL;
}
if ( isset ($Instance['___SOURCE_KEYS_'])) {
$Instance = $Instance['___SOURCE_KEYS_'];
}
$serdata = serialize ( $Instance );
list ($array_params, $array_elems) = explode ('{', $serdata, 2);
list ($array_tag, $array_count) = explode (':', $array_params, 3 );
$serdata = "O:".strlen ($Class).":\"$Class\":$array_count:{".$array_elems;
$Instance = unserialize ( $serdata );
return $Instance;
}
?>
With these ones you can do things like:
<?php
define("SFCMS_DIR", dirname(__FILE__)."/..");
require_once (SFCMS_DIR."/Misc/bless.php");
class Potatoe {
public $skin;
protected $meat;
private $roots;
function __construct ( $s, $m, $r ) {
$this->skin = $s;
$this->meat = $m;
$this->roots = $r;
}
function PrintAll () {
echo "skin = ".$this->skin."\n";
echo "meat = ".$this->meat."\n";
echo "roots = ".$this->roots."\n";
}
}
$Obj = new Potatoe ( 1, 2, 3 );
echo "<pre>\n";
echo "Using get_object_vars:\n";
$vars = get_object_vars ( $Obj );
print_r ( $vars );
echo "\n\nUsing obj2array func:\n";
$Arr = obj2array($Obj);
print_r ( $Arr );
echo "\n\nSetting all members to 0.\n";
$Arr['skin']=0;
$Arr['meat']=0;
$Arr['roots']=0;
echo "Converting the array into an instance of the original class.\n";
bless ( $Arr, Potatoe );
if ( is_object ($Arr) ) {
echo "\$Arr is now an object.\n";
if ( $Arr instanceof Potatoe ) {
echo "\$Arr is an instance of Potatoe class.\n";
}
}
$Arr->PrintAll();
?>
27-Oct-2004 10:02
actually, it's not entirely true that php5 will only return public members....php5 will return any variable IT HAS ACCESS TO
In other words, if you do a get_class_variables($this) inside a class, you'll get everything - public, private, the whole shebang...really annoying since you can't check to see what's private/public without using reflection
fbn79 at libero dot it
06-Apr-2004 07:26
In PHP5 it return only public variables.
manicdepressive AT mindless DOT com
05-Mar-2004 09:57
more strange, strange behaviour:
if you are trying to deep-copy an object with get_object_vars(), strange behaviour can accidentally clobber your original object properties. please read very, very carefully:
get_object_vars() may either return references to *or* deep copies of the object's properties *depending on whether that property has been set with the -> operator*. (this behaviour probably varies per php platform and os so please confirm for yourself.)
furthermore, consider
$properties = get_object_vars($obj);
normally, unset()ting a reference does not affect the original, i.e. $ref = NULL; is not the same as unset($ref); per the references documentation. However, if you have this strange references version and you unset() an array element of $properties, it will *SET THE OBJECT PROPERTY TO NULL*, which is not how references normally work.
even stranger behaviour comes into effect that i can only express with an example. please test this with your version and OS and proceed very carefully:
-->
<?php
echo "<pre>\n";
class Lump
{
var $size = 'average';
function & copy()
{ $copy = new Lump();
$properties = get_object_vars($this);
foreach( array_keys( $properties ) as $property ){
$copy->$property = $properties[$property]; }
return $copy;
}
}
$lump = new Lump();
$lump->size = 'huge'; $properties = get_object_vars($lump);
$properties['size'] = 'small'; echo "after changing the properties array:\n";
var_dump( $lump );
$original_lump = new Lump();
$original_lump->size = 'huge'; $other_lump =& $original_lump->copy();
unset( $other_lump->size );
echo "after unsetting in copy:\n";
var_dump( $original_lump ); echo "</pre>\n";
?>
code till dawn,
mark meves
christopher AT NOSPAM AT idealab DOT com
30-Dec-2003 05:12
Hmmm. A bit embarassing...
It turns out the best way to get references to all of your objects member variables is NOT with the functions I provided before, or with get_object_vars.
Just cast the object to array.
$a=(array)$obj;
# The two following statements are now equivalent and identical
$a["member"]=3;
$obj->member=3;
A very powerful tool, for inspectors and what not.
christopher AT NOSPAM AT idealab DOT com
23-Dec-2003 02:49
Please note that you cannot affect the object via the array values...in other words, the returned array does not contain references to the values within the object, but copies.
If you are making an object inspector or editor, this is not good enough. So I made the following methods:
METHODS:
function &getVar($obj, $name)
{
$expr="\$prop=&\$obj->$name;";
eval($expr);
return $prop;
}
function &getObjectVars($obj)
{
$result=array();
$vars=get_object_vars($obj);
foreach ($vars as $var => $value)
{
$result[$var]=&getVar(&$obj, $var);
}
return $result;
}
[NOTE: You must pass in a reference to an object, not an object. Sorry if this offends PHP'ers, but the distinction of pass-by-value and copy-on-assignment drives me batty (compared to Python, Java, Smalltalk), so I make all my functions pass by value, and force myself to pass in a reference to keep track of what is happening under the hood.]
EXAMPLE:
class Bob
{
function Bob()
{
$this->thing=13;
$this->other="whatever";
}
var $thing;
var $other;
}
$obj=&new Bob();
# NOTE: Passing in a reference!
$props=getObjectVars(&$obj);
$props["thing"]=-11;
var_dump($obj);
RESULTS:
object(bob)(2) {
["thing"]=>
&int(-11)
["other"]=>
&string(8) "whatever"
}
jordi at laigu dot net
06-Nov-2003 07:21
In case your object contains again OBJECTS or ARRAYS:
function makeAssoc($res) {
if (is_object($res)) $res = get_object_vars($res);
while (list($key, $value) = each($res)) {
if (is_object($value) || is_array($value)) {
$res[$key] = makeAssoc($value);
}
}
return $res;
}
Thanks to mark at dreamzpace dot com
markus at emedia-solutions-wolf dot de
06-Mar-2003 02:01
Hi,
I figured out that in prior version to 4.2 the returned array only contains attributes directly in this class, excluding the derived ones from parentclasses.
info at phpken dot de
21-Nov-2002 08:34
hello,
this example will look like all values of vars was set in your class. write a method like the name: dumpClass and then fill in follow code:
$vars = get_object_vars($this);
echo "<b>class vars</b>";
foreach( $vars as $name => $value ) {
echo "<li>".$name." : ".$value;
}
look at: get_object_vars($this);
andreas v.l
mark at dreamzpace dot com
13-Sep-2002 12:44
In case your object contains again objects (and so on), this function might be useful:
function makeAssoc($res) {
$res = get_object_vars($res);
while (list($key, $value) = each($res)) {
if (is_object($value)) {
$res[$key] = makeAssoc($value);
}
}
return $res;
}
nick_eby at bonzidev dot com
09-Jul-2002 02:13
Furthermore, variables not declared in the class but set on a given object, will be returned by get_object_vars().
Example, ver. 4.2.1:
<?
class MyTest {
var $classVar1 = 'Class Var 1';
var $classVar2;
var $classVar3;
function MyTest()
{
$this->classVar2 = 'class var 2';
}
}
$test = new MyTest();
$test->newObjVar = 'foobar';
echo "<pre>";
print_r(get_object_vars($test));
echo "</pre>";
?>
The output is:
Array
(
[classVar1] => Class Var 1
[classVar2] => class var 2
[classVar3] =>
[newObjVar] => foobar
)
Prior to version 4.2, classVar3 would not be output as it was never assigned a value.
michael at tapinternet dot com
13-Jun-2002 05:32
It seems that get_object_vars will now return properties of an object even if they have no value - meaning only defined by var $foo in the class declaration. This is noted behaviour in 4.2.1 which is different from previous versions and hitherto undocumented on this page.
florian at XCLUDETHISgsf dot de
29-Jan-2002 12:02
There is a strange behaviour, not sure whether it is a bug:
if I call
<?
$single_object = $data_array_of_objects[0];
$array_of_objectvars = get_object_vars($single_object);
foreach($array_of_objectvars as $key => $val) {
echo(" $key => $val<br>");
}
?>
I get only _ONE_ line with the $key = first variable name of the object and $val = the values of _ALL_ variables of the object including the first separated by a space.
NOW:
if I call
<?
$single_object = $data_array_of_objects[0];
$array_of_objectvars = get_object_vars($single_object);
foreach($array_of_objectvars as $key => $val) {
echo(" $key => $val<br>");
}
echo($data_array_of_objects[0]->objectvar1."<br>");
echo($data_array_of_objects[0]->objectvar2."<br>");
?>
I get a list of $key = $ val as expected, before the other echos' are printed.
It seems to me that get_object_vars works differently when you access a variable in those objects explicitly (as in the echos)
| |