php物件導向怎樣寫執行個體呢?

來源:互聯網
上載者:User
看了幾天物件導向 也大概知道一點物件導向的知識了 可是就是不知道在實際運用中是怎麼樣實現的 怎樣寫一些簡單的小例子呢 比如__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;

你可以在方法裡任意發揮想象,只是盡量遵循參數和傳回值的規範。有一個例子,就是將類的數組屬性轉換成一組獨立屬性

  • 相關文章

    聯繫我們

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