類是我們隊一組對象的描述
在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