Class clarifications (long one)
Posted: Fri Mar 24, 2006 6:40 am
I dont have a problem as such - anymore, I'm starting to get to grips with classes but there are a few questions I hope someone can answer for me that I havn't been able to figure out myself.
I've been using the example viewtopic.php?t=8873.
I have a class file
and a file of functions
conn.php contains the db connection variables.
I've simplified this but you get the idea. My questions are:
1)Why do the echoed variables in the class file echo twice?
2)Why, if I change to do they still print out twice but the second set have no variables assigned and throw an undeclared variable warning?
3)Is it not possible to place all of the require files and class instantiating code at the beginning of the file, meaning all of the functions can use them?
Or does each function need to instantiate the class with a unique variable?
As when I tried to do this I got the 'undefined function and call to a member function on a non_object ' (for the fetch function), the 'Cannot redeclare class' error, or a database connection error(which only happened after the sql was put into a function).
I have been reading up on all of this, from this forum too, but i still cant work it out so if anyone can enlighten me that would be great.
rj
I've been using the example viewtopic.php?t=8873.
I have a class file
Code: Select all
class DB_Class {
var $db;
function DB_Class($hostname ,$dbname, $username, $password) {
echo "hostname " . $hostname . "<BR>";
echo "dbname " . $dbname . "<BR>";
echo "username " . $username . "<BR>";
echo "password " . $password . "<BR>";
$this->db = mysql_connect ($hostname, $username, $password)
or die ("Unable to connect to Database Server");
mysql_select_db ($dbname, $this->db)
or die ("Could not select database");
}
function fetch($query) {
.....
}
}Code: Select all
function getuser(){
require "../../../conn.php";
require_once "./db.class.php";
$dbs = new DB_Class($hostname_myconnection, $database_myconnection, $username_myconnection, $password_myconnection);
$my_tags = $dbs->fetch("SELECT `*` from users WHERE user_id=2");
}I've simplified this but you get the idea. My questions are:
1)Why do the echoed variables in the class file echo twice?
2)Why, if I change
Code: Select all
require "../../../conn.php";Code: Select all
require_once "../../../conn.php";3)Is it not possible to place all of the require files and class instantiating code at the beginning of the file, meaning all of the functions can use them?
Or does each function need to instantiate the class with a unique variable?
As when I tried to do this I got the 'undefined function and call to a member function on a non_object ' (for the fetch function), the 'Cannot redeclare class' error, or a database connection error(which only happened after the sql was put into a function).
I have been reading up on all of this, from this forum too, but i still cant work it out so if anyone can enlighten me that would be great.
rj