我将Database.php和Config.php放在同一个位置。在Database.php中,如果我执行以下操作,则可以使用
<?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);
}
如果我将常量移动到Config.php并将上面的内容更改为以下
<?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);
}
它失败了,未定义的类常量&#39; DB_ADAPTER&#39;在Database.php中(如果我删除DB_ADAPTER,它将在下一个常量上失败)。
为什么会这样?
由于
更新
<?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";
}
答案 0 :(得分:1)
你不应该在没有对象创建的情况下使用 static和 public吗?
<?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";
}