开发者

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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜