2013-11-03 192 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')); 
    } 
}