當前位置:才華齋>設計>網頁設計>

關於PHP var-dump遍歷物件屬性的函式與應用程式碼

網頁設計 閱讀(2.66W)

關於PHP var-dump遍歷物件屬性的函式與應用程式碼

關於PHP var-dump遍歷物件屬性的函式與應用程式碼

文章下面我們要為你提供二種關於遍歷物件屬性方法,並且舉例說明遍歷物件屬性在php中的'應用。可以看出私有變數與靜態變數時獲取不到的,只有定義為公共變數才可以讀出來。

遍歷物件屬性第一種方法:

複製程式碼 程式碼如下:

<?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=';

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) ""

}

array(4) {

["a"]=>

NULL

["b"]=>

int(1)

["c"]=>

string(8) ""

["d"]=>

NULL

}

var_dump使用注意事項:

為了防止程式直接將結果輸出到瀏覽器,可以使用輸出控制函式來捕獲此函式的輸出,並把它們儲存到一個例如 string 型別的變數中。

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)

*/

?>