PHP中STDCLASS的使用方法詳解

來源:互聯網
上載者:User

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


如下代碼所示:

PHP

$tanteng = new stdClass();
$tanteng->name = 'tanteng';
$tanteng->email = 'xxx@qq.com';
 
$info = get_object_vars($tanteng);
print_r($info);exit;
輸出:

Array ( [name] => tanteng [email] => xxx@qq.com )

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

PHP

$tanteng = array();
$tanteng['name'] = 'tanteng';
$tanteng['email'] = 'xxx@qq.com';
可以這樣理解:stdClass是一個內建類,它沒有成員變數,也沒有成員方法的一個類。new一個stdClass就是執行個體化了一個『空』對象,它本身沒什麼意義,但是用stdClass定義有什麼好處呢?

如下代碼:

PHP

$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的方式可以節省記憶體開銷。

運行結果:

PHP

stdClass Object
(
    [name] => flypig
    [hehe] => hehe
)
stdClass Object
(
    [name] => flypig
    [hehe] => hehe
)
stdClass Object
(
    [name] => flypig
    [hehe] => hehe
)
從結果可以看出,改變$myUser的屬性確實改變了$user聲明的stdClass屬性。而如果$user是一個數組,賦值給$myUser,那就拷貝了一個副本給$myUser,這樣增大系統開銷。

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

PHP

$hehe['he1'] = 'he1';
$hehe['he2'] = 'he2';
 
$hh = (object) $hehe;
 
print_r($hh);
列印結果:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.