PHP中的stdClass

來源:互聯網
上載者:User

  如果所有的Class都應該存在於一個預設的層級中的話,那麼最頂層應該是最為一般的Class,也就是說極為抽象的,每一個下層的Class均比其上層的Class(即父類)更加專門化。基於該思想,在PHP中,這個頂層的Class被命名為“stdClass”,且作為一個“Standard Class”,你可以把它看成是一個不含任何屬性和方法的類。

 

使用stdClass的目的: 在運行時添加屬性到基底物件(Base Object)

  1. 問題
    你想建立一個對象,並在其中添加一些屬性,但是你卻不想把它作為一個明確的類正式地定義它。這一點在一些情況下是相當有用的,例如當你需要定義一個方法來返回帶有某些屬性(不確定的)的對象時,就如同從mysql_fetch_object( ) 或者 imap_header( )的使用一樣。
  2. 解決方案
    使用PHP內建類,stdClass:[php] view plaincopyprint?
    1. $pickle = new stdClass;
    2. $pickle->type = 'fullsour';

    $pickle = new stdClass;<br />$pickle->type = 'fullsour';

  3. 討論
    建立一個stdClass類型的對象,其不含有任何屬性和方法,就像array( )返回一個空數組一樣。
    你可以為其建立一個新的屬性並分配給它某個值,然後檢查它的值。[php] view plaincopyprint?
    1. $guss = new stdClass;
    2. $guss->location = 'Essex';
    3. print "$guss->location/n";
    4. $guss->location = 'Orchard';
    5. print "$guss->location/n";

    $guss = new stdClass;<br />$guss->location = 'Essex';<br />print "$guss->location/n";<br />$guss->location = 'Orchard';<br />print "$guss->location/n";
    方法,無論如何在一個對象被初始化之後再去定義它。但是在你想使用一個像從資料庫結果集中提取出來的對象(mysql_fetch_object方法,畢竟在調用它是你並不像真正地去請求資料庫)這樣的一般對象時,建立 stdClass 對象是非常有用的。如下:[php] view plaincopyprint?

    1. function pc_format_address($obj) {
    2. return "$obj->name <$obj->email>";
    3. }
    4. $sql = "SELECT name, email FROM users WHERE id=$id";
    5. $dbh = mysql_query($sql);
    6. $obj = mysql_fetch_object($dbh);
    7. print pc_format_address($obj);

    function pc_format_address($obj) {<br /> return "$obj->name <$obj->email>";<br />}</p><p>$sql = "SELECT name, email FROM users WHERE id=$id";<br />$dbh = mysql_query($sql);<br />$obj = mysql_fetch_object($dbh);<br />print pc_format_address($obj);
    pc_format_address方法使用一個對象的name 和 email 屬性,然後使其格式化後返回(如上代碼)。下面我們不調用mysql_fetch_object方法,應該如何使用呢?[php] view plaincopyprint?

    1. $obj = new stdClass;
    2. $obj->name = 'Adam Trachtenberg';
    3. $obj->email = 'adam@example.com';
    4. print pc_format_address($obj);

    $obj = new stdClass;<br />$obj->name = 'Adam Trachtenberg';<br />$obj->email = 'adam@example.com';<br />print pc_format_address($obj);

  4. 最後, 這種在運行時為一個Null 物件設定屬性的用法,不難看出也會給我們帶來一些問題,如你無法真正確定這個對象是誰,目的是什麼。http://blog.csdn.net/crazyjeff_liu/article/details/4046070
相關文章

聯繫我們

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