php中的類、對象

類是咱們隊一組對象的描述php

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

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

接下來就能夠產生這個類的實例:this

$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對象的實例。實際上也就是從抽象到具體的過程。code

對類和對象的一些理解:對象

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

打印student對象get

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

序列化對象io

$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";}

反序列化對象function

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

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

相關文章
相關標籤/搜索