get_object_vars() - php 类对象函数
get_object_vars()
(PHP 4, PHP 5, PHP 7)
返回由对象属性组成的关联数组
说明
get_object_vars(object $obj): array返回由$obj指定的对象中定义的属性组成的关联数组。
Note:在 PHP 4.2.0 之前的版本中,如果在$obj对象实例中声明的变量没有被赋值,则它们将不会在返回的数组中。而在 PHP 4.2.0 之后,这些变量作为键名将被赋予NULL
值。
使用get_object_vars()
以上例程会输出:
Array ( [x] => 1.233 [y] => 3.445 [label] => ) Array ( [x] => 1.233 [y] => 3.445 [label] => point #1 )
参见get_class_methods()和get_class_vars()。
参数
$objectAn object instance.
返回值
Returns an associative array of defined object accessible non-static properties for the specified$objectin scope. If a property have not been assigned a value, it will be returned with aNULL
value.
更新日志
版本 | 说明 |
---|---|
5.3.0 | This function now returnsNULLif the$objectisn't an object. |
prior to 5.3.0 | If the$objectisn't an object,thenget_object_vars()would returnFALSE |
prior to 4.2.0 | If the variables declared in the class of which the$objectis an instance, have not been assigned a value, those will not be returned in the array |
范例
Use ofget_object_vars()
以上例程会输出:
array(2) { ["b"]=> int(1) ["c"]=> NULL } array(4) { ["a"]=> NULL ["b"]=> int(1) ["c"]=> NULL ["d"]=> NULL }
参见
get_class_methods()
返回由类的方法名组成的数组get_class_vars()
返回由类的默认属性组成的数组
You can still cast the object to an array to get all its members and see its visibility. Example: 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: I've created also a bless function that works similar to Perl's bless, so you can further recast the array converting it in an object of an specific class: With these ones you can do things like:
Hi all, I just wrote a function which dumps all the object propreties and its associations recursively into an array. Here it is.. Example: You have an object like this: fruitsbasket Object ( [Fruits] => Array ( [0] => fruits Object ( [_name] => Mango [_color] => Green [_weight] => 10 ) [1] => fruits Object ( [_name] => Apple [_color] => Red [_weight] => 15 ) [2] => fruits Object ( [_name] => Grape [_color] => Purple [_weight] => 5 ) ) [total_weight] => 30 ) just do: it will produce an array: Array ( [Fruits] => Array ( [0] => Array ( [_name] => Mango [_color] => Green [_weight] => 10 ) [1] => Array ( [_name] => Apple [_color] => Red [_weight] => 15 ) [2] => Array ( [_name] => Grape [_color] => Purple [_weight] => 5 ) ) [total_weight] => 30 ) I wish function like this could be usefull for you all. :)
You can use call_user_func() to return public variables from inside the class: class Test { protected $protected; public $public; private $private; public function getPublicVars () { return call_user_func('get_object_vars', $this); } } $test = new Test(); var_dump($test->getPublicVars()); // array("public" => NULL)
get_object_vars() has confusing behaviour when called as get_object_vars($this) or similar: since a method inside a class definition can access private vars, apparently so can get_object_vars(), so it returns private vars as well. A simple workaround is to define a method that in itself calls get_object_vars, like:
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
It seems like there's no function that determines all the *static* variables of a class. I've come out with this one as I needed it in a project: It relies on an interesting property: the fact that get_object_vars only returns the non-static variables of an object.
A simple way to call this function within an Object and to only export the *public* params would be to artificially change the scope - for example with a closure in php 5.3:
function to convert object (with children) to an (associative) array ... recusive Example / Usage: a) return an associative (recusive) array from object $new_arr1 = object_to_array_recusive($my_object); // --- or --- object_to_array_recusive($my_object,TRUE); // --- or --- object_to_array_recusive($my_object,1); b) return a numeric (recusive) array from object (set 2nd argument = FALSE) $new_arr2 = object_to_array_recusive($my_object,FALSE); you can pre-set the Array-Value of Empty (Sub-) Objects in 3rd argument ($empty) // --- eg: NULL --- object_to_array_recusive($my_object,1,NULL);
If your object contains a reference, beware that you might get references for all object properties in the array values, thus when changing values in the array, they may change the object too (confirmed and not yet fixed PHP bug https://bugs.php.net/bug.php?id=66961 affecting all PHP versions up to at least 5.6.2 and 5.5.18 and 5.4.34). This 10-years old comment tried reporting this: http://php.net/manual/en/function.get-object-vars.php#40515 but its exemple was incomplete. See bug report for example.
class A{ private $priA; protected $proA; public $pubA; } class B extends A{ private $priB; protected $proB; public $pubB; public function getVars(){ return array_diff_key(get_object_vars($this), get_class_vars(get_parent_class($this))); } } $b = new B(); var_dump($b->getVars()); array(3) { ["priB"]=> NULL ["proB"]=> NULL ["pubB"]=> NULL }
get_object_vars($this) php5.3 + it returns only public and protected; NOT private vars
Note that before PHP 5.3.9 numeric object variables of unserialized object are not public, and get_object_vars() won't return them: https://bugs.php.net/bug.php?id=61774
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.
Be aware of the fact that this is scope-sensitive. If you're calling this from an objects own method, then private and protected vars will be outputted as well. Call it from outside the object and the result will most likely be what you want to archive.
If you're using the SPL ArrayObject class (or similar, or the ArrayAccess interface), you may have noticed that it's difficult to loop through an object's properties. get_object_vars does not return the properties of an ArrayObject. The only workaround I can see is to use get_class_vars. So, to iterate over the properties of an ArrayObject, and not the array values:
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" }
Just thought I would pass this on. Working with PHP 5.2.4 In Windows this works by reading the vars from the passed in object and copying them to the vars of the current object. public function copyMe(User $user) { $varArray = get_object_vars($this); $copyVarArray = get_object_vars($user); foreach ($varArray as $key=>$value) { $this->$key = $copyVarArray[$key]; } } This did not work in Linux, I had to add another function to return the array of vars. Calling get_array_vars on the passed in object would return an empty array. public function copyMe(User $user) { $varArray = $this->getArray(); $copyVarArray = $user->getArray(); foreach ($varArray as $key=>$value) { $this->$key = $copyVarArray[$key]; } } public function getArray() { return get_object_vars($this); }
function conv_obj($Data){ if(is_object($Data)){ foreach(get_object_vars($Data) as $key=>$val){ if(is_object($val)){ $ret[$key]=conv_obj($val); }else{ $ret[$key]=$val; } } return $ret; }elseif(is_array($Data)){ foreach($Data as $key=>$val){ if(is_object($val)){ $ret[$key]=conv_obj($val); }else{ $ret[$key]=$val; } } return $ret; }else{ return $Data; } } Very simple function to convert any Subobject to an array. Created it while working with Soap. For me as an beginner with PHP, very useful :o)
To follow the code of d11wtq (enquiries AT chriscorbyn.co.uk). I did this function to inspect all properties(public, private, protected) of object. Note: remember that static properties are not visible to the object. By that not supported to them
There is a strange behaviour, not sure whether it is a bug: if I call 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 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)
I find this function very helpful, What i wanted to do was to get the object properties of an exception so i could sanitize them for output. try { throw new Exception( 'Test Exception.', 100 ); } catch( Exception $e ) { var_dump( ( object ) get_object_vars( ( object ) ( new ArrayObject( $e ) ) -> getarrayCopy() ) ); } Example return: object(stdClass)#10 (4) { ["message"]=> string(15) "Test Exception." ["code"]=> int(100) ["file"]=> string(29) "C:\xampp\htdocs\dev\index.php" ["line"]=> int(19) }
If you want to access all properties (private, protected, public) of a class and his base class(es) from outside the object you can take a look in the code below. You can even reffrence them. Example:
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!
内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)