Specifically, I'm trying to reference a variable from an
include file I set up from within a class....
The include file (testdb.php) has:
$dbhost="localhost";
$dbuser="testdb";
$dbpass="x31X.23fw3f2";
$dbname="testDB";
And the class file has:
<?php
class myTestDB
{
function load_data()
{
require_once('./inc/testdb.php');
mysql_connect("$dbhost","$dbuser","$dbpass") or die("Unable to connect to Database");
print "db name is $dbname\n";
@mysql_select_db("$dbname");
print "dbname is $dbname\n";
When I run this method, it returns:
"db name is dbname is "
Even when I put the include or require clauses within the load_data() method the aforementioned variables
don't seem to be accessible.
This makes it obvious to me that the method, for whatever reason, isn't registering the
variables in the include file. If I do this on the top of the class file (myTestDB.class.php), the dbhost & dbuser & dbpass
variables are perfectly accessible. I guess my variable scope understanding is a bit rusty or
something. Can someone please shed some light on this situation?
Thank you in advance for your help!
Notice that in the revised code below, the first line of load_data()
is "global $dbhost, $dbuser, $dbpass;"
This tells PHP that you will reference those global variables from
within the function.
<?php
require_once('./inc/testdb.php');
class myTestDB
{
function load_data()
{
global $dbhost, $dbuser, $dbpass;
mysql_connect("$dbhost","$dbuser","$dbpass") or die("Unable to
connect to Database");
print "db name is $dbname\n";
@mysql_select_db("$dbname");
Cheers,
Kevin