我有这样的代码:
//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' ;
在首页,并添加global $EXAMPLE;
后,但$EXAMPLE
是空的,为什么?
使用require
,而不是require_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;
}
}
要求您的文件在__construct
方法内。所以require一次需要文件一次在try1
方法。
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;
}
}