PHP OOP:从子对象调用方法父对象

PHP OOP:从子对象调用方法父对象,php,oop,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->

我上过这门课

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();

没有运气。谢谢

您应该将creaing$db提取到方法(createConnection),即:

然后您可以使用提取方法:

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'));
    }
}

作为一种良好实践,您应该明确地将构造函数声明为public

您没有重写子构造函数,因此使用父构造函数

子对象继承受保护的父对象属性


因此,您可以使用$this->db访问父对象的数据库对象。

您可以克隆该对象吗?谢谢$这个->数据库工作。感谢您的良好实践;)
class WebController extends Controller {
    public function login()
    {
        $user = new \DB\SQL\Mapper($this->db, 'users');
        $auth = new \Auth($user, array('id'=>'username', 'pw'=>'password'));
    }
}