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?
Than开发者_开发技巧ks in advance
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.
Look into the Singleton Design Pattern. You should not have the need to use globals
, as you seem to know it is not necessary.
精彩评论