php中stdclass怎麼使用?

PHP中STDCLASS在我們開發應用中使用到的不多,但是PHP中STDCLASS作用是非常的大的,下面我們一起來看PHP中STDCLASS的用法.

在WordPress中很多地方使用stdClass來定義一個對象(而通常是用數組的方式),然後使用get_object_vars來把定義的對象『轉換』成數組.

如下代碼所示:

$tanteng = new stdClass();
$tanteng->name = 'tanteng';
$tanteng->email = '[email protected]';
$info = get_object_vars($tanteng);
print_r($info);
exit;

輸出:

Array ( [name] => tanteng [email] => [email protected] )

get_object_vars的作用是返回由對象屬性組成的關聯數組。它的效果跟這樣定義數組其實是一樣的:

$tanteng = array();
$tanteng['name'] = 'tanteng';
$tanteng['email'] = '[email protected]';

可以這樣理解:stdClass是一個內置類,它沒有成員變量,也沒有成員方法的一個類,new一個stdClass就是實例化了一個『空』對象,它本身沒什麼意義,但是用stdClass定義有什麼好處呢?

如下代碼:

$user = new stdClass();
$user->name = 'gouki';
$user->hehe = 'hehe';
$myUser = $user;
$myUser->name = 'flypig';
print_r($user);
print_r($myUser);
print_r($user);

這裏$myUser被賦值$user,但其實並沒有新開闢一塊內存存儲變量,$myUser還是指的stdClass這個對象,通過$myUser改變屬性頁就改變了$user的屬性,並不是新建一個副本,如果程序中有許多這樣的操作,使用stdClass的方式可以節省內存開銷.

運行結果:

stdClass Object
(
  [name] => flypig
  [hehe] => hehe
)
stdClass Object
(
  [name] => flypig
  [hehe] => hehe
)
stdClass Object
(
  [name] => flypig
  [hehe] => hehe
)

從結果可以看出,改變$myUser的屬性確實改變了$user聲明的stdClass屬性,而如果$user是一個數組,賦值給$myUser,那就拷貝了一個副本給$myUser,這樣增大系統開銷.

當然,你也可以反過來,把一個數組轉換爲對象:

$hehe['he1'] = 'he1';
$hehe['he2'] = 'he2';
$hh = (object) $hehe;
print_r($hh);

打印結果:

stdClass Object ( [he1] => he1 [he2] => he2 )

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章