[英]How to access global variable from inside class's function
我有文件init.php
:
<?php
require_once 'config.php';
init::load();
?>
与config.php
:
<?php
$config = array('db'=>'abc','host'=>'xxx.xxx.xxx.xxxx',);
?>
一个名为something.php
的类:
<?php
class something{
public function __contruct(){}
public function doIt(){
global $config;
var_dump($config); // NULL
}
}
?>
为什么它为空?
在php.net中,他们告诉我,我可以访问,但实际上不是。 我试过但不知道。 我使用的是PHP 5.5.9。
config.php
的变量$config
不是全局的。
为了使它成为一个全局变量,我不建议你必须在它面前写出global
的魔术词。
我建议你阅读超全局变量 。
还有一点变量范围 。
我建议的是建立一个处理你的课程。
那看起来应该是这样的
class Config
{
static $config = array ('something' => 1);
static function get($name, $default = null)
{
if (isset (self::$config[$name])) {
return self::$config[$name];
} else {
return $default;
}
}
}
Config::get('something'); // returns 1;
像这样使用Singleton Pattern
<?php
class Configs {
protected static $_instance;
private $configs =[];
private function __construct() {
}
public static function getInstance() {
if (self::$_instance === null) {
self::$_instance = new self;
}
return self::$_instance;
}
private function __clone() {
}
private function __wakeup() {
}
public function setConfigs($configs){
$this->configs = $configs;
}
public function getConfigs(){
return $this->configs;
}
}
Configs::getInstance()->setConfigs(['db'=>'abc','host'=>'xxx.xxx.xxx.xxxx']);
class Something{
public function __contruct(){}
public function doIt(){
return Configs::getInstance()->getConfigs();
}
}
var_dump((new Something)->doIt());
包括这样的文件:
include("config.php");
class something{ ..
并将数组打印为var_dump($config);
不需要全球化。
稍微更改您的类以在构造函数上传递变量。
<?php
class something{
private $config;
public function __contruct($config){
$this->config = $config;
}
public function doIt(){
var_dump($this->config); // NULL
}
}
?>
然后,如果你
config.php
yourClassFile.php
和做,
<?php
$my_class = new something($config);
$my_class->doIt();
?>
它应该工作。
注意:不使用Globals
总是好的(在我们可以避免它们的地方)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.