views:

328

answers:

3

I have defined some constants eg:

define('DB_HOSTNAME', 'localhost', true);
define('DB_USERNAME', 'root', true);
define('DB_PASSWORD', 'root', true);
define('DB_DATABASE', 'authtest', true);

now when I try to do this:

class Auth{
function AuthClass() {
$this->db_link = mysql_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD) 
or die(mysql_error());
}
}

I get an error. Why is this and what do I need to do?

See, I've tried using (for example) global DB_HOSTNAME but this fails with an error.

EDIT

the error I am getting is Unknown MySQL server host 'DB_HOSTNAME' (1)

+3  A: 

When the script runs, both the constant and the class definitions should be included.

e.g.

constants.php.inc

define('DB_HOSTNAME', 'localhost', true);
define('DB_USERNAME', 'root', true);
define('DB_PASSWORD', 'root', true);
define('DB_DATABASE', 'authtest', true);

Auth.php.inc

class Auth{
    function AuthClass() {
        $this->db_link = mysql_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD) 
           or die(mysql_error());
    }
}

script.php

include "constants.php.inc";
include "Auth.php.inc";

//do stuff
Artefacto
Umm. That really doesn't do anything to address the issue since classes do not recognize variables set outside the scope of the class. All this does is reorganize the information with exactly the same result.
Joseph
@Joseph Constants aren't variables, and they are indeed recognized inside any function/method that is executed after they are defined. This is a valid answer and may indeed answer the question.
meagar
the above answer is the problem I have
Ashley Ward
@Ashley Ward see here http://codepad.viper-7.com/WcDT6R As you can see, you can access defined define's inside a class.
Artefacto
You are correct and I am humbled. There must be other errors with my code.
Ashley Ward
I stand corrected as well. Deleting my answer so as not to misdirect other seekers.
Joseph
+1  A: 

It should work as long as you've defined the constants before AuthClass() runs. If they are not in the same file as your Auth class, you will first need to include them within the file that Auth resides in so it can see them:

include("the_file_that_has_those_constants_in_it.php");

Then it should just work. Constants are already global so there is no need to use the global keyword.

alexantd
A: 
meagar