What is the use of constructor in abstract class in php

前端 未结 1 1449
我在风中等你
我在风中等你 2021-02-13 15:46

I followed this link already before asking - Answer is in JAVA context and this for constructor in PHP .

Since I am starter, my implementation of my PHP code in OOP conc

相关标签:
1条回答
  • 2021-02-13 16:21

    Constructor in abstract class is the same as in concrete class. Use constructors when they are needed, for example, if you need to intialize some data or assign some resources.

    I'll give you an example:

    abstract class Db
    {
        protected $pdo;
    
        public function __construct($pdo)
        {
            $this->pdo = $pdo;
        }
    
        abstract function select($table, $fields);
    }
    
    class Db_Mysql extends Db
    {
        public function select($table, $fields)
        {
            // Build MySQL specific select query
            // then execute it with $this->pdo
        }
    }
    
    class Db_Pgsql extends Db
    {
        public function select($table, $fields)
        {
            // Build PostgreSQL specific select query
            // then execute it with $this->pdo
        }
    }
    
    // Usage:
    $db = new Db_Mysql($pdo);
    
    $db->select('users', array('id', 'name'));
    
    0 讨论(0)
提交回复
热议问题