如何從類的函數內部訪問全局變量 (How to access global variable from inside class's function)


問題描述

如何從類的函數內部訪問全局變量 (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

  1. include config.php
  2. 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 BurkeVasil RashkovAlexander GofmanDanyal SandeelomasterFly)

參考文件

  1. How to access global variable from inside class's function (CC BY‑SA 2.5/3.0/4.0)

#php-5.5 #PHP






相關問題

當作為參數傳遞時,PHP 如何解釋和評估函數和匿名函數? (How does PHP interpret and evaluate function and anonymous function when passed as an argument?)

使用 symfony 時 PHP 5.5 無法識別服務器 (PHP 5.5 won't recognise server when using symfony)

升級到 PHP5.5 時 Wordpress 崩潰 (Wordpress crashes when upgrading to PHP5.5)

從數據庫返回多個值 (return multiple values from database)

PHP:嵌套 foreach 循環的問題 (PHP: Issue with nested foreach loops)

如果條件在幾小時、幾天內不起作用 (if condition not working for Hours,Days)

Slim 3.3 輸出中缺少字符 (Slim 3.3 missing characters in output)

PHP排序對象值但保留原始相對順序 (PHP sort objects value but retain original relative order)

遇到錯誤無法加載請求的文件:helpers/form_validation_helper.php (An Error Was Encountered Unable to load the requested file: helpers/form_validation_helper.php)

如何從類的函數內部訪問全局變量 (How to access global variable from inside class's function)

如何修改輸出緩衝區? (How to modify output buffer?)

在同一台 Ubuntu 服務器上安裝和配置 PHP5 和 7 (Install and configure PHP5 and 7 on same Ubuntu server)







留言討論