Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to pass DB object into class that is extended numerous 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 my $db object that is instantiated in another file but wish to somehow pass this into class a's functions without using the global keyword everytime i define a new function in class "a".

I know i can do this by passing the DB object when instantiating class X and Y, then passing it through to class A that way (like im currently doing with the tablename and column), however i never know how many times i might extend class A and thought that there must be another easier way somehow.

Does anybody know of a better solution that i could consider to achieve this?

Thanks in advance

like image 963
phpNutt Avatar asked Feb 02 '26 14:02

phpNutt


2 Answers

You could use PHP's static properties.

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

Now that property will be shared across all instances of that object and it's children.

like image 173
runfalk Avatar answered Feb 05 '26 02:02

runfalk


Look into the Singleton Design Pattern. You should not have the need to use globals, as you seem to know it is not necessary.

like image 40
Jim Avatar answered Feb 05 '26 03:02

Jim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!