我当然尝试了一下$GLOBALS
,但仍然没有成功。我的语法正确吗?我的理解是,这$DB_USER
是在全球范围内。
<?php
$DB_USER = 'foo';
class Database
{
// this does not work
private $DB_USER = $GLOBALS['DB_USER'];
private $DB_PASS = 'foob';
private $DB_DRIVER = 'foob_foob';
// ...
您是$DB_USER
从类方法内部调用的,这意味着您实际上是从本地范围(在类内)调用变量的。要解决此问题,只需告诉PHP您正在通过在要使用全局变量的global $DB_USER
方法内部添加(或使用构造函数将其添加到类范围中)来寻找全局变量:
class Database
{
private $DB_USER = '';
private $DB_PASS = 'foob';
private $DB_DRIVER = 'foob_foob';
// snip
// Method 1: Add the variable to the class scope with the constructor
public function __construct()
{
global $DB_USER;
$this->DB_USER = $DB_USER;
}
// Method 2: tell PHP that you want the global variable in your methods
public function foo()
{
$global $DB_USER;
...
}
使用方法1,您现在可以调用$this->DB_USER
而不是$GLOBALS['DB_USER']
。
使用方法2,您将其添加global $DB_USER
到每个方法,然后仅使用$DB_USER
。
有关更多信息,请参见http://php.net/manual/zh/language.variables.scope.php
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句