php中的類、對象

來源:互聯網
上載者:User
類是我們隊一組對象的描述

在php裡,每個類的定義都以關鍵字class開頭,後面跟著類名,緊接著一對花括弧,裡麵包含有類成員和方法的定義。如下代碼所示

class person{    public $name;    public $gender;    public function say(){        echo $this->name."is ".$this->gender;    }}

接下來就可以產生這個類的執行個體:

$student = new person();$student->name="Tome";$student->gender= "male";$student->say();$teacher= new person();$teacher->name="kati";$teacher->gender= "female";$teacher->say();

這段代碼則執行個體化了person類,產生了一個student對象和teacher對象的執行個體。實際上也就是從抽象到具體的過程。

對類和對象的一些理解:

  • 類定義了一系列的屬性和方法,並提供了實際的操作細節,這些方法可以用來對屬性進行加工。
  • 對象含有類屬性的具體值,這就是類的執行個體化。正是由於屬性的不同,才能區分不同的對象。在上面例子裡,由於student和teacher的性別和姓名不一樣,才得以區分開二人。
  • 類與對象的關係類似一種服務於被服務、加工與被加工的關係,具體而言,就如同原材料與流水線的關係。只需要在對象上調用類中所存在的方法,就可以對類的屬性進行加工,並且展現其功能。

列印student對象

print_r((array)$student);var_dump($student);

序列化對象

$str = serialize($student);echo $str;file_put_contents('store.txt',$str);輸出結果:0:6:"person":2:{s:4:"name";s:3:"Tom";s:6:"gender";s:4:"mail";}

還原序列化對象

$str = file_get_contents('store.txt');$student = unserialize($str);$student->say();

轉載自:http://www.9958.pw/post/php_class

  • 聯繫我們

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