简体   繁体   中英

PHP: Call abstract class method in another class

I hope to be very clear!

I have dbFacile class who fetch, insert and work with my DB.

$db = dbFacile::open( 'mysql', DATABASE, USERNAME, PASSWORD, HOST );

$db->fetchRows('select * from my_stores')

I've created another class where i want to get an $array with all of my stores from table my_stores.

class Stores {
    public $s_table = 'my_stores';
    public $rows;
    public function get_all_stores (){      
        $this->rows = $db->fetchRows('select * from $this->s_table');
        foreach($rows as $row) {
            echo $row['name'] . '<br />';
        }
    }
}

I've tried to initiate dbFacile in my get_all_stores method but that class is abstract and i can't.

From it's unit tests folder of the github repository you can see the new intended usage is:

$db = \dbFacile\factory::mysql();
$db->open(DATABASE, USERNAME, PASSWORD, HOST);
$db->fetchRows('select * from my_stores');
...

An example using your class:

class Stores {
private $s_table = 'my_stores';
private $db;

public function __construct($db)
{
    $this->db = $db;
}

public function get_all_stores (){
    $rows = $this->db->fetchRows(sprintf('select * from %s', $this->s_table));
    //do your stuff with rows and maby return $rows 
 }
}

$db = \dbFacile\factory::mysql();
$db->open(DATABASE, USERNAME, PASSWORD, HOST);

//usage
$stores = new Stores($db);
$stores->get_all_stores();

The way you want to do it is to inject $db in the Stores class via its constructor

class Stores {
  private $db;
  public function __construct(className $db) {
    $this->db = $db;
  }
}

where className should be the full namespace class name of dbFacile base class. So that PHP throws an error whenever you try to instantiate Stores with the wrong dependency.

This way you're injecting your dependency in the Stores class and you can use $this->db wherever you want inside that class.

You could pass db object into Stores via constructor. Read about dependency injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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