【发布时间】:2014-03-23 03:46:27
【问题描述】:
简单的问题。我对 OOP 还是很陌生,基本上是在学习基础知识。我有一个 config.php 文件,写在下面。
<?php
$hName = 'localhost'; // Hostname :]
$dbName = 'db'; // Database
$tbAdmin = 'admin'; // Table administrator
$tbPosts = 'posts'; // Table posts
$dbUser = 'phpadmin'; // Database login uname
$dbPass = 'phpadmin'; // Database login pw
?>
这是我的functions.php文件:
class databaseEstablish {
public $dbc;
/**
* Connect to database (make a connection)
* @return boolean Return true for connected / false for not connected
*/
public function connect() {
require_once 'config.php';
$this->host = $hName;
$this->username = $dbUser;
$this->password = $dbPass;
$this->database = $dbname;
$this->dbc = @mysqli_connect($this->host, $this->username, $this->password, $this->database);
}
虽然这可能必须工作,但错误消息会出现在输出中(点替换路径,以及其他三个点替换行,它们是波纹管'require config.php':
Notice: Undefined variable: hName in ... ...
Notice: Undefined variable: dbUser in ... ...
Notice: Undefined variable: dbPass in ... ...
Notice: Undefined variable: dbname in ... ...
我是否必须对配置文件使用类和公共函数或构造函数,如果不是,有什么问题?据我所知,这些是配置文件中的全局变量,应该可以从任何其他文件访问。谢谢。
【问题讨论】:
-
包含/必需的文件被视为在执行要求/包含时它们的内容实际上是文件的一部分。没有明显的理由为什么您的大多数 var 不应该按书面形式提供,除非您在包含的文件中有
$dbName,并且在类中有$dbname- PHP 变量区分大小写。当然,如果您在其他地方已经有require_once该文件,则此时不需要它。试试require或include。
标签: php oop global-variables