PHP遍历对象属性方法与var_dump应用
本文将介绍两种在PHP中遍历对象属性的方法,并通过具体案例说明其在实际应用中的表现。从结果可以看出,私有变量和静态变量无法被直接获取,只有定义为公共(public)的变量才能被读取出来。
第一种遍历对象属性的方法实现如下:
代码示例:
<?php
class foo {
private $a;
public $b = 1;
public $c;
private $d;
static $e;
public function test() {
var_dump(get_object_vars($this));
}
}
$test = new foo;
var_dump(get_object_vars($test));
$test->test();
?> 运行结果如下:
array(2) {
["b"]=>
int(1)
["c"]=>
NULL
}
array(4) {
["a"]=>
NULL
["b"]=>
int(1)
["c"]=>
NULL
["d"]=>
NULL
}
第二种遍历对象属性的方法实现如下:
代码示例:
<?php
class foo {
private $a;
public $b = 1;
public $c='jb51.net';
private $d;
static $e;
public function test() {
var_dump(get_object_vars($this));
}
}
$test = new foo;
var_dump(get_object_vars($test));
$test->test();
?> 运行结果如下:
array(2) {
["b"]=>
int(1)
["c"]=>
string(8) "jb51.net"
}
array(4) {
["a"]=>
NULL
["b"]=>
int(1)
["c"]=>
string(8) "jb51.net"
["d"]=>
NULL
}
使用var_dump时的注意事项:
为了避免程序直接将结果输出到浏览器页面,可以使用输出控制函数来捕获该函数的输出内容,并将其保存到如字符串类型的变量中。
var_dump实例代码演示
代码示例:
<?php
$a = array (1, 2, array ("a", "b", "c"));
var_dump ($a);
/* 输出:
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
}
*/
$b = 3.1;
$c = TRUE;
var_dump($b,$c);
/* 输出:
float(3.1)
bool(true)
*/
?>