php中stdClass的用法分析_PHP教程

來源:互聯網
上載者:User

php中stdClass的用法分析


這篇文章主要介紹了php中stdClass的用法,執行個體分析了stdClass的功能及提示,具有一定參考借鑒價值,需要的朋友可以參考下

本文執行個體分析了php中stdClass的用法。分享給大家供大家參考。具體分析如下:

stdclass在php中是預定義的幾個類之一,是zent保留的一個類。實際上它是PHP提供的一個基類,就是一個空白的類,裡面什麼都沒有,我們可以執行個體化它,然後定義一系列的變數,通過它來進行變數的傳遞(很多php程式員用它來傳遞一系列變數的值,而同時又懶得去建立一個自己的類)。但是,由於執行個體化後不能添加方法,只能傳遞屬性。因為,一旦類被實列化以後,就不能在添加方法了。

stdclass可以作為基類使用,其最大特點是,(其衍生類別)可以自動新增成員變數,而無須在定義時說明。

一切php變數都是stdClass的執行個體。

使用方法:

1、使用stdclass:

?

1

2

3

4

5

$andy = array();

$andy = (object)$andy;

$andy->a = 1;

$andy->b = 2;

$andy->c = 3;

這樣數量a、b、c就填進了stdclass裡面。這樣要省事,因為建立空對像卻要$andy = new Andy; 而且還得先有個class Andy{}。又如:

?

1

2

3

4

5

6

$a = new stdClass();

$a->id = '11 ';

$a->username = 'me';

print_r($a);

?>

將會輸出:stdClass Object ( [id] => 11 [username] => me ) 。
很多時候用這種方法取代數組的使用,只不過是換一種文法形式。

2、讀取:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

stdClass Object

(

[getWeatherbyCityNameResult] => stdClass Object

(

[string] => Array

(

[0] => 四川

[1] => 成都

[2] => 56294

[3] => 56294.jpg

[4] => 2009-5-17 13:52:08

[5] => 26℃/19℃

[6] => 5月17日 陰轉陣雨

)

)

)

其實和array差不多,只是訪問方式改變一點就行,我們一般習慣使用array['key']這種方式來訪問數組。
對於這種stdClass來說,如上例,$weather->getWeatherbyCityNameResult->string[0]可以這樣來訪問屬性,這個將得到結果“四川”。

3、執行個體化,new。

對比這兩個代碼:

?

1

2

3

4

5

6

7

$a = array(1=>2,2=>3);

$a = (object)$a;

$a->id = '11 ';

$a->username = 'me';

print_r($a);

?>

將輸出:stdClass Object ( [1] => 2 [2] => 3 [id] => 11 [username] => me ) 。

?

1

2

3

4

5

6

7

8

$a = array(1=>2,2=>3);

$a = (object)$a;

$a = new stdClass();

$a->id = '11 ';

$a->username = 'me';

print_r($a);

?>

將輸出:stdClass Object ( [id] => 11 [username] => me ) 。

原來用new執行個體化後,前面的數組清空,只留下後面添加進來的,如果不執行個體化,stdClass將保留所有元素。

需要注意的是,在函數裡面使用global、static時遇new stdclass引用的情況,這時&new stdclass將會失效,應避免使用引用,直接用new stdclass。

希望本文所述對大家的php程式設計有所協助。

http://www.bkjia.com/PHPjc/961777.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/961777.htmlTechArticlephp中stdClass的用法分析 這篇文章主要介紹了php中stdClass的用法,執行個體分析了stdClass的功能及提示,具有一定參考借鑒價值,需要的朋友可以參...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.