PHP:获取 class 的私有字段列表(不是实例!)
PHP: Get list of private fields of a class (not instance!)
如何在没有实例但只有 class 名称的情况下迭代 class 的私有字段?
get_object_vars
需要现有实例。
你可以简单地做:
class Foo
{
public $public = 1;
protected $protected = 2;
private $private = 3;
}
$refClass = new \ReflectionClass('Foo');
foreach ($refClass->getProperties() as $refProperty) {
if ($refProperty->isPrivate()) {
echo $refProperty->getName(), "\n";
}
}
或使用实用程序隐藏实现 function/method:
/**
* @param string $class
* @return \ReflectionProperty[]
*/
function getPrivateProperties($class)
{
$result = [];
$refClass = new \ReflectionClass($class);
foreach ($refClass->getProperties() as $refProperty) {
if ($refProperty->isPrivate()) {
$result[] = $refProperty;
}
}
return $result;
}
print_r(getPrivateProperties('Foo'));
// Array
// (
// [0] => ReflectionProperty Object
// (
// [name] => private
// [class] => Foo
// )
//
// )
如何在没有实例但只有 class 名称的情况下迭代 class 的私有字段?
get_object_vars
需要现有实例。
你可以简单地做:
class Foo
{
public $public = 1;
protected $protected = 2;
private $private = 3;
}
$refClass = new \ReflectionClass('Foo');
foreach ($refClass->getProperties() as $refProperty) {
if ($refProperty->isPrivate()) {
echo $refProperty->getName(), "\n";
}
}
或使用实用程序隐藏实现 function/method:
/**
* @param string $class
* @return \ReflectionProperty[]
*/
function getPrivateProperties($class)
{
$result = [];
$refClass = new \ReflectionClass($class);
foreach ($refClass->getProperties() as $refProperty) {
if ($refProperty->isPrivate()) {
$result[] = $refProperty;
}
}
return $result;
}
print_r(getPrivateProperties('Foo'));
// Array
// (
// [0] => ReflectionProperty Object
// (
// [name] => private
// [class] => Foo
// )
//
// )