問題描述
如何從類的函數內部訪問全局變量 (How to access global variable from inside class's function)
我有文件 init.php
:
<?php
require_once 'config.php';
init::load();
?>
with 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。
參考解法
方法 1:
The variable $config
in config.php
is not global.
To make it a global variable, which i do NOT suggest you have to write the magic word global
in front of it.
I would suggest you to read superglobal variables.
And a little bit of variable scopes.
What I would suggest is to make a class which handles you this.
That should look something like
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;
方法 2:
Use Singleton Pattern like this
<?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());
方法 3:
Include the file like this:
include("config.php");
class something{ ..
and print the array as var_dump($config);
no need of global.
方法 4:
Change your class a bit to pass a variable on the constructor.
<?php
class something{
private $config;
public function __contruct($config){
$this‑>config = $config;
}
public function doIt(){
var_dump($this‑>config); // NULL
}
}
?>
Then, if you
- include
config.php
- include
yourClassFile.php
and do,
<?php
$my_class = new something($config);
$my_class‑>doIt();
?>
It should work.
Note: It is always good not to use Globals
(in a place where we could avoid them)
(by Haruji Burke、Vasil Rashkov、Alexander Gofman、Danyal Sandeelo、masterFly)