A simple way to pass a DB object to a class that extends many times

Consider the following PHP code:

<?php
require_once("myDBclass.php");
class a {
    private $tablename;
    private $column;
    function __construct($tableName, $column) {
        $this->tableName = $tablename;
        $this->column = $column;        
    }

    function insert() {
        global $db;
        $db->query("INSERT INTO ".$this->tableName." (".$this->column.") VALUES (1)");  
    }       
}

class x extends a {
    function __construct() {
        parent::construct("x", "colX"); 
    }
}

class y extends a {
    function __construct() {
        parent::construct("y", "colY"); 
    }
}
?>

I have a $ db object that is being created in another file, but wanted to somehow pass this to a function class without using the global everytime keyword. I am defining a new function in class "a".

I know I can do this by passing the DB object when creating instances of class X and Y, and then passing it to class A (e.g. im currently with a table name and column), however I never know how many times I can expand class A and thought that somehow there should be another simpler way.

Does anyone know of a better solution that I could consider to achieve this?

Thanks in advance

+3
2

Singleton. globals, , .

+1

PHP .

class A {
    static $db;
    public static function setDB($db) {
        self::$db = $db;
    }
}

, .

+2

Source: https://habr.com/ru/post/1762967/


All Articles