在PHP方法中包含外部变量
我有以下代码:在PHP方法中包含外部变量,php,global-variables,require-once,Php,Global Variables,Require Once,我有以下代码: //config.php $EXAMPLE['try1'] = "...." ; $EXAMPLE['try2'] = "...." ; 因此,我有另一个带有php类的文件: class try { public function __construct() { if($this->try1() && $this->try2()){ return true; } } public
//config.php
$EXAMPLE['try1'] = "...." ;
$EXAMPLE['try2'] = "...." ;
因此,我有另一个带有php类的文件:
class try {
public function __construct() {
if($this->try1() && $this->try2()){
return true;
}
}
public function try1(){
require_once 'config.php' ;
echo $EXAMPLE['try1'];
return true;
}
public function try2(){
require_once 'config.php' ;
echo $EXAMPLE['try2'];
return true;
}
}
但在我的例子中,
$EXAMPLE['try1']
是,但是$EXAMPLE['try2']
为空。。。为什么?我已经尝试过包含require_once'config.php'代码>在首页,并在全局$EXAMPLE之后添加
,但$EXAMPLE
始终为空,为什么?使用require
,而不是require\u once
。否则,如果在一个函数中加载该文件,则不会在另一个函数中加载该文件,因此无法获取变量
最好是完全要求函数之外的函数。然后将$EXAMPLE
声明为全局变量
require_once 'config.php';
class try {
public function __construct() {
if($this->try1() && $this->try2()){
return true;
}
}
public function try1(){
global $EXAMPLE
echo $EXAMPLE['try1'];
return true;
}
public function try2(){
global $EXAMPLE
echo $EXAMPLE['try2'];
return true;
}
}
在\u构造方法中需要您的文件。因此,require once需要文件once intry1
方法
class try {
private $_example = array();
public function __construct() {
require_once 'config.php';
$this->_example = $EXAMPLE;
return $this->try1() && $this->try2();
}
public function try1(){
echo $this->_example['try1'];
return true;
}
public function try2(){
echo $this->_example['try2'];
return true;
}
}
不要忘记检查数组键是否为isset:isset($this->_示例['try1'])
;