編輯:
看來你使用的是自己的PHP對象的屬性是什麼定義,所以讓我給你我的。
PHP文檔對於主題有些模糊,有些功能如get_object_vars
有點誤導,因爲它們將獲取對象屬性而不是變量。
據我的理解,是什麼它歸結爲是:PHP使得類性能之間的區別(在編譯時已知),並動態特性(即設置沒有那些已被宣佈)。
它與設置屬性有關(因爲它會創建一個動態的屬性),但重點是要知道屬性是否在類定義內部聲明。
如果實際上你感興趣的類和對象屬性之間的這種差異,你可能會發現API的快樂,儘管如果你問我,我發現它使用起來極其尷尬。
此API的主要優點是,您可以列出將從當前範圍(通常爲受保護或私有成員)無法訪問的屬性。
如果您只是使用get_object_vars
或get_class_vars
函數,則會忽略所有私有/受保護屬性,除非您在對象本身內定義一個方法(繼承調用get_class_vars
的類將允許您獲取受保護的屬性,但不能訪問私有那些)。
function list_properties($obj, $filter = null)
{
if ($filter === null) $filter = ReflectionProperty::IS_STATIC
| ReflectionProperty::IS_PUBLIC
| ReflectionProperty::IS_PROTECTED
| ReflectionProperty::IS_PRIVATE;
$spy = new ReflectionClass ($obj);
$class_properties = $spy->getProperties($filter);
echo "class:<br />";
foreach ($class_properties as $prop)
{
$name = $prop->getName();
$p = $spy->getProperty ($name);
$p->setAccessible(true);
$value = $p->getValue($obj);
echo "$name ("; var_dump($value); echo ")<br />";
}
echo "<br />object:<br />";
foreach ($obj as $property => $value)
{ echo "$property ("; var_dump($value); echo ")<br />"; }
}
class foo {
protected $class_protected;
private $class_private;
public $class_public;
private static $static_protected = "azerty";
private static $static_private = "qsdfgh";
public static $static_public = "wxcvbn";
}
$v = new foo();
$v->dynamic = "xxx";
list_properties($v);
// the ReflectionClass filter flags semantic is broken,
// so filtering becomes soon a cruel pain in the *ss
/*
* I leave it to the reader as an execrise to coax the bloody thing
* into giving you only the static public class properties, for instance.
*/
list_properties($v, ReflectionProperty::IS_STATIC|ReflectionProperty::IS_PUBLIC);
一種方法是將您的屬性轉換爲該類內的本地數組。好處是可以使用array_filter(),它將返回一個數組減去原始數組中的空鍵。 http://us2.php.net/manual/en/function.array-filter.php – Rottingham
@kuroineko http:// stackoverflow。com/questions/21050862 /高效的方法來檢查堆棧的非空屬性#comment31651251_21050976 – user2679413