我想打印/ rcho一个没有递归的对象的即时成员。 print_r()以递归方式打印成员。你知道这个功能吗?
答案 0 :(得分:0)
为什么不尝试instanceof
?
<?php
class A
{
}
$obj = new A();
if ($obj instanceof A) {
echo 'Yes I am !';
}
if ($obj1 instanceof A) {
}
else
{
echo "No am not !";
}
输出:
Yes I am !
No am not !
答案 1 :(得分:0)
如果我理解正确,您希望回显对象的属性,只要它们不是另一个对象或数组。
可以使用reflection完成此操作。
class A
{
public $test1;
protected $test2;
private $test3;
public $test4;
public function __construct()
{
$this->test1 = 1;
$this->test2 = 2;
$this->test3 = 3;
$this->test4 = new stdClass();
$this->test4->prop1 = 1;
$this->test4->prop2 = 2;
}
}
$obj = new A();
// our control - what you have at the moment:
print_r($obj);
结果如下:
A Object
(
[test1] => 1
[test2:protected] => 2
[test3:A:private] => 3
[test4] => stdClass Object
(
[prop1] => 1
[prop2] => 2
)
)
以下,使用反射:
$refl = new ReflectionObject($obj);
$properties = $refl->getProperties();
foreach ($properties as $property) {
// ensure we can also access protected and private properties
$property->setAccessible(true);
$value = $property->getValue($obj);
if (!is_object($value) && !is_array($value)) {
echo $property->getName() . ': ' . $value . PHP_EOL;
}
}
结果:
test1: 1
test2: 2
test3: 3