Using a cute object into another object without make it GLOBAL?
My friend adviced me: Jesus, man! Don't use GLOBALs. It makes your software slow.
This is my way:
// Database class
class DB extends mysqli { ...开发者_开发问答 }
// create Database object
$db = new DB(...)
// My class
class A {
function foo(){
global $db; ## PROBLEM IS HERE
$db->get_all(...);
}
}
Is there any way to use $db
object without make it GLOBAL? or should I stop to listen to my friend?
Sure. Just create a property for your $db
object and pass it into object A
, via the constructor (or create a setter method):
class A
{
protected $db;
public function __construct($db)
{
$this->db = $db;
}
function foo()
{
$this->db->get_all(...);
}
}
// create your objects. inject the DB object into object A
$db = new DB();
$a = new A($db);
Is this what you mean?
精彩评论