看了幾天物件導向 也大概知道一點物件導向的知識了 可是就是不知道在實際運用中是怎麼樣實現的 怎樣寫一些簡單的小例子呢 比如__get和__set在實際工作中是怎麼用的呢
回複內容:
看了幾天物件導向 也大概知道一點物件導向的知識了 可是就是不知道在實際運用中是怎麼樣實現的 怎樣寫一些簡單的小例子呢 比如__get和__set在實際工作中是怎麼用的呢
還沒更新完。。。
如果你為一張表寫映射
1、剛開始你可以這麼寫
class Table { public $id = NULL; public $title = NUll;}
$table = new Table();$table->id = 1000;$table->title ='映射';var_dump($table);
2、資料表更變了,加了一個created_at,於是怎麼辦?改檔案還是?
於是這個是不是更方便?
class Table { public function __set($property,$value){ return $this->$property = $value; }}
$table = new Table();$table->id = 1000;$table->title = 'PHP裡__set()怎麼用?';$table->created_at = time();var_dump($table);
3、從資料庫中映射出來行(大概示意下)
class Table { public $tableName = NULL; public function loadFromMysqlRowResult($row){ foreach($row as $property=>$value){ $this->__set($property,$value); } return $this; } public function __set($property,$value){ return $this->$property = $value; }}class News extends Table { private $db = NULL; public function __construct($db){ $this->db = $db; $this->tableName = strtolower(__CLASS__); } public function findOne($id){ $query = $this->db->query("select * from news where id=".$id)->fetch(PDO::FETCH_ASSOC); return self::loadFromMysqlRowResult($query); } }$db = new PDO('mysql:host=localhost;dbname=test','root','c313c313');$newsModel = new News($db);$news = $newsModel->findOne(1);echo $news->title;
你可以在方法裡任意發揮想象,只是盡量遵循參數和傳回值的規範。有一個例子,就是將類的數組屬性轉換成一組獨立屬性