作者JYHuang (夏天到了,冷不起来了说)
看板PHP
标题Re: [请益] 由::呼叫时自动产生建构式
时间Wed Apr 18 00:40:02 2012
※ 引述《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