Page 1 of 1
Objects in Classes
Posted: Tue Feb 13, 2007 4:53 pm
by chris12295
Is it possible to instantiate an object inside a class?
I want a db reader class to create a new mysqli but
I get an error. Is this possible?
Posted: Tue Feb 13, 2007 4:57 pm
by feyd
Not only is it possible, it's a pretty normal activity.
Post your code.

Posted: Tue Feb 13, 2007 4:58 pm
by blackbeard
Yes, you can. What exactly is the error?
Posted: Tue Feb 13, 2007 5:17 pm
by chris12295
Code: Select all
<?php
class user
{
private $host = "****";
private $username = "****";
private $password = "****";
private $database = "****";
private $db = new mysqli($host, $username, $password, $database);
function __construct() {
}
}
?>
and the error is: Parse error: syntax error, unexpected T_NEW in users/inc/classes/class.user.php on line 10
Posted: Tue Feb 13, 2007 5:33 pm
by chris12295
also, is it possible to do something like
if i have already created a mysqli object elsewhere?
Posted: Tue Feb 13, 2007 5:38 pm
by RobertGonzalez
Read this manual page, just above figure 19.3...
Code: Select all
<?php
class user
{
private $host = "****";
private $username = "****";
private $password = "****";
private $database = "****";
// I AM ALMOST CERTAIN THIS IS YOUR PROBLEM...
private $db = new mysqli($host, $username, $password, $database);
function __construct() {
}
}
?>
Declare the var, then in the contructor, instantiate the object.
Posted: Tue Feb 13, 2007 5:39 pm
by Weirdan
Code: Select all
class user
{
private $host = "****";
private $username = "****";
private $password = "****";
private $database = "****";
private $db;
function __construct() {
$this->db = new mysqli($this->host, $this->username, $this->password, $this->database);
}
}
Posted: Tue Feb 13, 2007 5:42 pm
by feyd
If you're embracing OOP, don't use globals.

Posted: Tue Feb 13, 2007 5:43 pm
by chris12295
the above worked, is there anyway to be able to use $db instead of $this->db?
Posted: Tue Feb 13, 2007 5:49 pm
by RobertGonzalez
Not without globalizing. Why would you want to? Other than because you don't want to do a find and replace throughout the class and change all $db into $this->db...

Posted: Tue Feb 13, 2007 5:53 pm
by chris12295
well just to make typing easier, i dont like using $this->db->query() for example but I do like using mysqli as an object
Posted: Tue Feb 13, 2007 5:54 pm
by RobertGonzalez
Trust me, using $this->db->query is cake compared to $this->settings->get('object.mysql')->result->num_rows....
Posted: Tue Feb 13, 2007 5:55 pm
by chris12295
true. thanks for all the help.
Posted: Tue Feb 13, 2007 6:10 pm
by RobertGonzalez
You got it. Glad we could help.