简体   繁体   English

PHP OOP:从子级调用方法父级

[英]PHP OOP: calling method parent from child

I've this class 我上过这堂课

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

    }
}

and his child 和他的孩子

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

I need another $db object in WebController, you can note that for the moment i did duplicate code. 我需要在WebController中使用另一个$db对象,你可以注意到目前我做了重复的代码。

How i can recall the $db from parent without duplicate code? 我如何从没有重复代码的父级回忆$ db? I did try 我确实试过了

$db = parent::__construct();

without luck. 没有运气。 Thank you 谢谢

You should extract creaing $db to method (createConnection) ie.: 你应该提取creaing $ db到方法(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;
    }
}

And then you can use extracted method: 然后你可以使用提取的方法:

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

Or use connection created via constructor 或者使用通过构造函数创建的连接

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

You should explicitly declare your constructor as public as a matter of good practice. 您应该明确地将构造函数声明为公共的,这是一种良好的实践。

You are not overriding the constructor in the child and so the parent constructor is used. 您没有覆盖子项中的构造函数,因此使用了父构造函数。

The child inherits the parents properties which are protected. 子进程继承受保护的父属性。

Therefore you can use $this->db to access the database object of the parent. 因此,您可以使用$ this-> db来访问父级的数据库对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM