Nick Price
Nick Price

Reputation: 963

PHP undefined class for config file

I have Database.php and Config.php in the same location. In Database.php, if I do the following it works

<?php
class Database
{
    const DB_ADAPTER = 'mysql';
    const DB_USER = 'something';
    const DB_PASSWORD = 'something';
    const DB_DATABASE = 'something';
    const DB_HOST = "localhost";
    const DB_CHARSET = "utf8";

    /* All my code */

     $dns = self::DB_ADAPTER . ':host=' . self::DB_HOST . ';dbname=' . self::DB_DATABASE;
            self::$dbLink = new \PDO($dns, self::DB_USER, self::DB_PASSWORD);

}

If I move the constants to Config.php and change the above to the following

<?php

include('Config.php');

class Database
{
    /** @var PDO The shared database link. */
    protected static $dbLink;

    /* All my code */

     $dns = Config::DB_ADAPTER . ':host=' . Config::DB_HOST . ';dbname=' . Config::DB_DATABASE;
            self::$dbLink = new \PDO($dns, Config::DB_USER, Config::DB_PASSWORD);

} 

It fails with a Undefined class constant 'DB_ADAPTER' in Database.php (if i remove DB_ADAPTER, it will fail on the next constant).

Why would this be happening?

Thanks

UPDATE

<?php

/**
 * Class containing configuration details
 */
class Config
{
    const DB_ADAPTER = 'mysql';
    const DB_USER = 'something';
    const DB_PASSWORD = 'something';
    const DB_DATABASE = 'something_portal_db';
    const DB_HOST = "localhost";
    const DB_CHARSET = "utf8";
}

Upvotes: 0

Views: 168

Answers (1)

maxpovver
maxpovver

Reputation: 1600

Shouldn't you make them static and public to use without object creation?

<?php

/**
 * Class containing configuration details
 */
class Config
{
    public const DB_ADAPTER = 'mysql';
    public const DB_USER = 'something';
    public const DB_PASSWORD = 'something';
    public const DB_DATABASE = 'something_portal_db';
    public const DB_HOST = "localhost";
    public const DB_CHARSET = "utf8";
}

Upvotes: 1

Related Questions