俺の雑記帳

My random memorandumです。(つまり、個人的な備忘録であり、その点ご容赦を。)

property_exists()とget_object_vars()とforeach(オブジェクト)の動作の違い

オブジェクトのforeachは、get_object_vars()と反応ルールは同じ。(アクセス権のあるメンバ変数にはTRUE)。
property_exists()は、get_object_vars()より多くに反応する。(アクセス権有無無関係(PHP5.3以上)、static変数にも反応。(
メソッドは別(method_exists())))

参照:
http://php.net/manual/ja/function.property-exists.php
http://www.phppro.jp/phptips/archives/vol53/2


      1 <?php
2 class foo {
3 private $a;
4 public $b = 1;
5 public $c;
6 private $d;
7 static $e = 4;
8
9 public function test() {
10 var_dump(get_object_vars($this));
11 }
12 public function obj_foreach_echo(){
13 foreach($this as $_memberVarName => $_val){
14 echo $_memberVarName . " => '" . $_val . "'" . PHP_EOL;
15 }
16 }
17 public function obj_foreach_propertyexists($arr){
18 foreach ($arr as $_var){
19 print "property_exists({$_var}) : ";
20 var_dump(property_exists($this, $_var));
21 }
22 }
23 }
24
25 $test = new foo;
26 $test->B = 'dynamic';
27 var_dump(get_object_vars($test));
28 echo PHP_EOL;
29 foreach($test as $_memberVarName => $_val){
30 echo $_memberVarName . " => '" . $_val . "'" . PHP_EOL;
31 }
32 echo PHP_EOL;
33 foreach(["a","b","c","d","e","f","B"] as $_var){
34 print "property_exists({$_var}) : ";
35 var_dump(property_exists($test, $_var));
36 }
37 echo PHP_EOL;
38 echo PHP_EOL;
39 $test->test();
40 echo PHP_EOL;
41 $test->obj_foreach_echo();
42 echo PHP_EOL;
43 $test->obj_foreach_propertyexists(["a","b","c","d","e","f","B"]);
44 echo PHP_EOL;
45 echo_PHP_EOL;
46 foreach(["a","b","c","d","e","f","B"] as $_var){
47 print "property_exists({$_var}) : ";
48 var_dump(property_exists("foo", $_var));
49 }
50 ?>
実行結果:
[*******@tvm1560 php]$ /usr/local/php/bin/php -f foreach-object_VS_get_object_vars_VS_property_exists.php
array(3) {
["b"]=>
int(1)
["c"]=>
NULL
["B"]=>
string(7) "dynamic"
}

b => '1'
c => ''
B => 'dynamic'

property_exists(a) : bool(true)
property_exists(b) : bool(true)
property_exists(c) : bool(true)
property_exists(d) : bool(true)
property_exists(e) : bool(true)
property_exists(f) : bool(false)
property_exists(B) : bool(true)


array(5) {
["a"]=>
NULL
["b"]=>
int(1)
["c"]=>
NULL
["d"]=>
NULL
["B"]=>
string(7) "dynamic"
}

a => ''
b => '1'
c => ''
d => ''
B => 'dynamic'

property_exists(a) : bool(true)
property_exists(b) : bool(true)
property_exists(c) : bool(true)
property_exists(d) : bool(true)
property_exists(e) : bool(true)
property_exists(f) : bool(false)
property_exists(B) : bool(true)

property_exists(a) : bool(true)
property_exists(b) : bool(true)
property_exists(c) : bool(true)
property_exists(d) : bool(true)
property_exists(e) : bool(true)
property_exists(f) : bool(false)
property_exists(B) : bool(false)
[********@tvm1560 php]$