views:

26

answers:

2

Hey guys,

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

+1  A: 

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

Brad F Jacobs
I'm unsure how mentioning the singleton pattern helps him
Galen
If the database class was set us a singleton class then he could easily call `$db = db::singleton();` and viola, he now has the db class available to the class and better yet it is sure to be a single object instead of multiple / duplicate. And even better yet, he can use that object anywhere inside of his scripts, as long as the dbclass is included just by using that statement.
Brad F Jacobs
that's basically the same as using global $db;
Galen
Yea, after some reading, I understand what you are getting at. Going to do some research and see if I cannot come up with a better answer cause now I am a bit intrigued. If, however, you have a better answer please enlighten us to it.
Brad F Jacobs
A: 

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.

antennen