开发者

How to access constant defined outside class?

I have defined some constants eg:

define('DB_HOSTNAME', 'localho开发者_运维问答st', 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.

The error I am getting is:

Unknown MySQL server host 'DB_HOSTNAME' (1)


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


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.


It sounds like your constants aren't being defined before you instantiate class Auth. When you use an undefined constant this way, PHP will issue a warning and convert it to a string. If the problem is indeed that your constants aren't defined, your code will effectively be interpreted as:

$this->db_link = mysql_connect('DB_HOSTNAME', 'DB_USERNAME', 'DB_PASSWORD');

Given the error you're getting (Unknown MySQL server host 'DB_HOSTNAME'), I'm assuming this is what's happening.

As other answers state, make sure you're defining the constants before you attempt to call Auth::AuthClass. If the class and the DB_* constants are defined in different files, make sure that both files are included before you attempt to instantiate/use class Auth.


As an aside, defined constants are not variables. You cannot use global CONSTANT_NAME; in this way, and you do not need to - all constants are always global, and available everywhere after the point they're defined. A simple test proves this:

define ('MY_CONST', 3);

class Test {
    function __construct() { echo MY_CONST; }
}

$x = new Test(); // outputs 3
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜