2013-11-03 184 views
0

調用方法父我有這個類PHP OOP:從孩子

class Controller { 

    protected $f3; 
    protected $db; 


    function __construct() 
    { 

     $f3=Base::instance(); 

    $db=new \DB\SQL('mysql:host=62.xxx;port=3306;dbname=Sqlxxx','xxxx','xxxxx'); 

    $this->f3=$f3; 
    $this->db=$db; 

    $this->db->exec('SET CHARACTER SET utf8'); 
    $this->db->exec('SET time_zone = \'+00:00\''); 

    } 
} 

和他的孩子

class WebController extends Controller { 
    public function login() 
    { 
     $db=new \DB\SQL('mysql:host=62.xxx;port=3306;dbname=Sqlxxx','xxxx','xxxxx'); 
     $user = new \DB\SQL\Mapper($db, 'users'); 
     $auth = new \Auth($user, array('id'=>'username', 'pw'=>'password')); 
    } 
} 

我需要WebController另一個$db對象,你可以注意到,目前我沒有重複的代碼。

我可以從父母記得$ db沒有重複的代碼?我曾嘗試過

$db = parent::__construct(); 

沒有運氣。謝謝

+0

你可以克隆該對象? –

回答

1

您應該明確聲明您的構造函數是公共的,作爲一個很好的實踐蒂斯。

您不重寫子構造函數,因此使用父構造函數。

孩子繼承受保護的父母屬性。

因此,您可以使用$ this-> db來訪問父級的數據庫對象。

+0

謝謝。 $ this-> db的作品。並感謝你的良好做法;) – sineverba

1

你應該提取creaing $分貝方法(的createConnection),即:

class Controller { 
    protected $f3; 
    protected $db; 


    function __construct() 
    { 
     $this->f3=Base::instance(); 
     $this->db=$this->createConnection(); 
    } 
    protected function createConnection() { 
     $db = new \DB\SQL('mysql:host=62.xxx;port=3306;dbname=Sqlxxx','xxxx','xxxxx'); 
     $db->exec('SET CHARACTER SET utf8'); 
     $db->exec('SET time_zone = \'+00:00\''); 
     return $db; 
    } 
} 

然後你就可以使用提取方法:通過構造

創建

class WebController extends Controller { 
    public function login() 
    { 
     $db=$this->createConnection(); 
     $user = new \DB\SQL\Mapper($db, 'users'); 
     $auth = new \Auth($user, array('id'=>'username', 'pw'=>'password')); 
    } 
} 

或者使用連接

class WebController extends Controller { 
    public function login() 
    { 
     $user = new \DB\SQL\Mapper($this->db, 'users'); 
     $auth = new \Auth($user, array('id'=>'username', 'pw'=>'password')); 
    } 
}