2014-01-23 55 views
-2
class example 
{ 

    public $one; 
    public $two; 
    public $object; 

    public function __construct() 
    { 
     $this->object = new MyObject(); 
    } 

} 

如何在PHP中获取类的所有非对象属性?

$example = new example(); 
var_dump(get_object_vars($example)); // returns $one,$two,$object 

我怎样才能得到它不是对象的所有属性?

UPDATE

对于那些谁投下来,我的意思是递归!

如何递归获取exampleMyObject的所有属性?我的意图是编写一个代码来找出两个PHP对象之间的区别。

+0

'array_filter'结果。 – Wrikken

回答

1
$properties = array_keys(array_filter(get_object_vars($example), function($element) { 
    return !is_object($element); 
})); 

和递归算法

function getMyObjectVars($obj) { 
    $properties = array(); 
    foreach (get_object_vars($obj) as $k => $v) { 
     if (is_object($v)) { 
      $properties = array_merge($properties, getMyObjectVars($v)); 
     } else { 
      $properties[] = $k; 

     } 
    } 
    return $properties; 
} 

print_r(getMyObjectVars($example)); 
0
foreach(get_object_vars($example) as $prop){ 
    if(!is_object($prop)){ 
     echo $prop; 
    } 
} 
0
$props = get_object_vars($example); 
$nonObjProps = array(); 
foreach($props as $prop) 
{ 
    if (is_object($prop)) 
    { 
     continue; 
    } 
    $nonObjProps = $prop; 
} 
相关问题