看板 PHP 關於我們 聯絡資訊
※ 引述《gpmm (銀色)》之銘言: : 好吧…雖然我覺得這已經很 dirty code 了… XD : class Model { : private $bar; : function __construct () { : $this->bar = 'foo'; : } : function getbar () { : if (! isset ($this)) { : $m = new Model (); : return $m->getbar (); : } : else : return $this->bar; : } : } : $bar = Model::getbar (); : 看看這是不是你要的 :Q 看起來滿接近當初看到的那個方法的 :p 整理了一下今天一直在寫的那支Class 主要的問題還是在架構上沒有寫的很好。 大至上的架構和會用到的Method是這樣 Class Profile{ private $db; private $pic_path; public $user_info; public $user_id; public function __construct($uid){ $this->db = new db() // pdo; $this->user_id = $uid; $this->pic_path = path; self::user_info(); } public user_info(){ $sql = 'select * from user where uid='.$this->user_id'; $this->user_info = $this->db->getrow($sql); } public get_pic($uid){ $pic = $tihs->pic_path.$this->user_id.".jpg"; if (!file_exitsts($pic)){ if ($this->user_info->sex = 'male') return 'boy.jpg'; else return 'girl.jpg'; } } } 一都會先 $user = new Profile($uid); echo "hello ".$user->user_info->name; echo "<img src='".$user->get_pic."'>"; 來取得使用者本身的資訊和圖片 後來想要取得其它使用者的圖片時 想直接呼叫來取得 echo "<img src='".Profile::get_pic($uid)."'>"; 這樣會有pic_path和user_info未被建構而無法取得的問題。 嗯.. 這樣的話是要怎麼去架構整個class會比較好呢? 把pic跟profile切開用繼承的方式去寫嘛? 還是在get_pic裡做判斷再做建構? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.255.135.150