note 72084 deleted from function.mysqli-connect by hholzgra

From: Date: Sat, 29 Sep 2007 10:36:39 +0000
Subject: note 72084 deleted from function.mysqli-connect by hholzgra
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-130913@lists.php.net to get a copy of this message
Note Submitter: Eamon Straughn ---- Many here have said you can't produce a persistent connection, however this is false if you are using objects take below as an example with strict visibility; sorry about no comments just quite busy but hope this helps someone who wants to broaden their perspective; class A { private $link; public $objects; //load all child objects with the connection public function __construct($classes, $db, $host, $user, $pass) { $this->link = $this->connect($db, $host, $user, $pass); $name = __CLASS__; foreach ($classes as $id => $obj) { if(is_subclass_of($obj,$name)) { $this->objects[$obj] = new $obj($this->link); } } private function connect($db, $host, $user, $pass) { $link = new mysqli($host,$user,$pass,$db); if($link->error) return "could not connect to database server, ". $link->error; else return $link; } public __destruct($void) { if($void) $this->link->close(); } } class B extends A { private $link; public function __construct($link) { $this->link = $link } function getUsers() { $q = $this->link->prepare("select id,name,location from users"); $q->execute(); $q->bind_result($id,$name,$location); $q->fetch(); return array($id,$name,$location); } } example of use: $classes = array('B'); $db = 'mydatabase'; $host = '127.0.0.1'; $user = 'username'; $pass = 'password'; $a = new A($classes, $db, $host, $user, $pass); extract($a->objects, EXTR_PREFIX_SAME, 'obj'); $b->getUsers(); this example allows you to initiate one instance of every object as long as it is a child with the same connection. this is just a snippet of a much bigger model.

« previous php.notes (#130913) next »