Objects in PHP including other objects
I think the title is right but please correct me if It is mis-leading.
The problem: I have a class which wants to use the DB class, now instead of having to "global $db;" in every method I wish to use the DB object I want to be able to place the object reference in my class properties.
Still following? OK here goes:
class user
{
private $id = 0;
private $name = NULL;
private $password = NULL;
private $db;
function __construct()
{
$this->load_db();
}
private function load_db()
{
global $db;
$this->$db =& $db;
}
I get an error "Object of class db could not be converted to string" which is annoying as I can't figure out how to set the var type in PHP...
Now my question is two fold:
1) How do I fix this. or 2) Is there a better way of doing it as this feels really "kack-handed".
Thanks in advance,
Dorjan
edit: Just to make sure I'm clear I do not want to make multiple instances of the same DB object. At least I believe this to be a good p开发者_开发问答ractice ^,^
If you're using $this, you only need one dollar sign. So $this->db
.
private function load_db()
{
global $db;
$this->db =& $db;
}
Also if you are using php 5 you dont need to use the =&
operator because objects are implicitly passed by reference. Secondly, you should inject $db
into the constructor or fetch it from a Registry object instead of using global
.
You should better do
class User
{
private $id = 0;
private $name = NULL;
private $password = NULL;
private $db;
function __construct($db=null)
{
$this->db = $db;
}
}
Note that you don't put a $
before variable names if you access properties via $object->
. That is were the error comes from.
To use a global inside a class method is really bad practice as you somehow tie your class to that global variable. Better pass it as a parameter to the constructor or a method.
Later you can instantiate the class with
$user = new User($db)
Also note that class names by convention start with a capital letter.
This:
$this->db
Inject the db instance through the constructor
public function __construct($db)
{
$this->db = $db;
}
Yopu'll want to use something called dependency injection. This is where you "inject" an object into another object to do whatever it is the object does. In this case do database stuff
class user { private $id = 0; private $name = NULL; private $password = NULL; private $db;
function __construct($database_object)
{
$this->load_db();
$this->$db = $database_object;
}
public function do_db_stuff()
{
$this->$db->doStuff();
}
$db = new Mysql()
$user = new User($db);
$user->do_db_stuff();
精彩评论