Php 如何从类内部访问全局变量';s函数
我有一个文件Php 如何从类内部访问全局变量';s函数,php,php-5.5,Php,Php 5.5,我有一个文件init.php: <?php require_once 'config.php'; init::load(); ?> <?php $config = array('db'=>'abc','host'=>'xxx.xxx.xxx.xxxx',); ?> <?php class something{ public function __contruct(){}
init.php
:
<?php
require_once 'config.php';
init::load();
?>
<?php
$config = array('db'=>'abc','host'=>'xxx.xxx.xxx.xxxx',);
?>
<?php
class something{
public function __contruct(){}
public function doIt(){
global $config;
var_dump($config); // NULL
}
}
?>
名为something.php
的类:
<?php
require_once 'config.php';
init::load();
?>
<?php
$config = array('db'=>'abc','host'=>'xxx.xxx.xxx.xxxx',);
?>
<?php
class something{
public function __contruct(){}
public function doIt(){
global $config;
var_dump($config); // NULL
}
}
?>
为什么为空?在php.net中,他们告诉我我可以访问,但实际上不是。 我试过了,但不知道。
我使用的是php 5.5.9。包括如下文件:
include("config.php");
class something{ ..
并将数组打印为
var_dump($config)
不需要全局变量。在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;
稍微更改您的类以在构造函数上传递变量
<?php
class something{
private $config;
public function __contruct($config){
$this->config = $config;
}
public function doIt(){
var_dump($this->config); // NULL
}
}
?>
它应该会起作用
注意:最好不要使用
Globals
(在我们可以避免它们的地方)像这样使用单例模式
<?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());
是否包含config.php
?只需包括和打印$ConfigHand-off globals!天啊!那么<代码> $CONFIG/<代码>不会被视为全局变量???我想我需要_once/include,然后PHP会将其视为全局变量。很好!谢谢我没有想到单身模式。谢谢你的建议。