如何制作PHP StdClass反射
我有一个将php变量记录到该文件的函数。有一个部分处理对象如何制作PHP StdClass反射,php,reflection,stdclass,Php,Reflection,Stdclass,我有一个将php变量记录到该文件的函数。有一个部分处理对象elseif(is_object($var))…,它可以很好地处理任何应用程序对象。但如果变量是StdClass的对象,则它不起作用。我不明白其他对象和StdClass对象之间的区别在哪里。以下是函数的代码: function varLog( $var, $log = 'info', $depth = 2, $round = 0) { $logFile = __DIR__ . '/../log/' . $log . '.log';
elseif(is_object($var))…
,它可以很好地处理任何应用程序对象。但如果变量是StdClass的对象,则它不起作用。我不明白其他对象和StdClass对象之间的区别在哪里。以下是函数的代码:
function varLog( $var, $log = 'info', $depth = 2, $round = 0)
{
$logFile = __DIR__ . '/../log/' . $log . '.log';
file_put_contents( $logFile, '(' . gettype( $var ) . ') ', FILE_APPEND );
if( in_array( gettype($var), ['integer', 'double', 'string'] ) )
{
file_put_contents( $logFile, $var . PHP_EOL, FILE_APPEND );
}
elseif( in_array( gettype($var), ['boolean', 'NULL'] ) )
{
$var = is_null( $var ) ? 'NULL' : ($var ? 'TRUE' : 'FALSE');
file_put_contents( $logFile, $var . PHP_EOL, FILE_APPEND );
}
elseif ( is_array( $var ) )
{
file_put_contents( $logFile, 'length ' . count($var) . PHP_EOL, FILE_APPEND );
foreach ( $var as $key => $val )
{
file_put_contents( $logFile, str_repeat(' ', $round + 1) . $key . ' => ', FILE_APPEND );
if ( $round + 1 <= $depth )
{
varLog( $val, $log, $depth, $round + 1 );
}
else
{
file_put_contents( $logFile, '(' . gettype( $val ) . ')' . PHP_EOL, FILE_APPEND );
}
}
}
elseif ( is_object( $var ) )
{
file_put_contents( $logFile, get_class( $var ) . PHP_EOL, FILE_APPEND );
$props = (new ReflectionClass( $var ))->getProperties();
foreach ( $props as $prop )
{
$prop->setAccessible( true );
$scoope = $prop->isPrivate() ? '(private)' : ($prop->isProtected() ? '(protected)' : '(public)');
file_put_contents( $logFile, str_repeat(' ', $round + 1) . $scoope . ' ' . $prop->name . ' => ', FILE_APPEND );
if ( $round + 1 <= $depth )
{
varLog( $prop->getValue( $var ), $log, $depth, $round + 1 );
}
else
{
file_put_contents( $logFile, '(' . gettype( $prop->getValue( $var ) ) . ')' . PHP_EOL, FILE_APPEND );
}
}
}
}
不会返回任何道具。PHP具有和。您可以对StdClass
使用ReflectionObject
$props = (new ReflectionObject(($var))->getProperties();
否则,您可以使用:
两者的区别在于
ReflectionClass
只返回类的原始属性
假设您有以下类:
class Test {
public $foo;
}
然后创建其实例并指定新属性:
$instance = new Test;
$instance->bar = 'foo';
[
ReflectionProperty {#3059
+name: "foo",
+class: "Test",
modifiers: "public",
},
]
然后,如果使用ReflectionClass
检索类的属性:
(new ReflectionClass($instance))->getProperties();
它不返回条
属性:
$instance = new Test;
$instance->bar = 'foo';
[
ReflectionProperty {#3059
+name: "foo",
+class: "Test",
modifiers: "public",
},
]
因此,将ReflectionClass
与StdClass
一起使用时,会出现空数组。而ReflectionObject
将同时返回:
(new ReflectionObject($instance))->getProperties();
输出为:
[
ReflectionProperty {#3071
+name: "foo",
+class: "Test",
modifiers: "public",
},
ReflectionProperty {#3073
+name: "bar",
+class: "Test",
modifiers: "public",
},
]
来源:您可以执行
获取对象变量($var)
如果需要,而不是对StdClass
使用ReflectionClass
。我想知道为什么此代码不能与StdClass一起使用。get\u object\u vars()只返回公共属性。