代码之家  ›  专栏  ›  技术社区  ›  nebkat

php所有函数变量全局

  •  4
  • nebkat  · 技术社区  · 14 年前

    我的网站上有一个名为init的函数,它位于名为functions.php的外部文件中。index.php加载该页并调用函数init:

    function init(){
       error_reporting(0);
       $time_start = microtime(true);
       $con = mysql_connect("localhost","user123","password123");
       mysql_select_db("db123");
    }
    

    如果可能的话,我如何在不必使用的情况下获得所有这些变量的全局性呢?

    global $time_start;
    global $con;
    
    4 回复  |  直到 14 年前
        1
  •  1
  •   sepehr GR7    14 年前

    如果你想特别使用globals,看看 $GLOBALS 数组。尽管有其他几种方法, Pass by reference , Data Registry Object 推荐 等。

    More on variable scopes .

        2
  •  3
  •   mathk    14 年前

    你不希望它全球化。

    另一种方法是将其封装到对象中,甚至使用DI来配置它。

        3
  •  1
  •   Romain Deveaud    14 年前

    也许您可以从init()函数返回这些变量:

    function init(){
       error_reporting(0);
       $time_start = microtime(true);
       $con = mysql_connect("localhost","user123","password123");
       mysql_select_db("db123");
    
       return array('time_start' => $time_start, 'con' => $con);
    }
    
        4
  •  0
  •   Babiker    14 年前

    您可以在全局范围内声明它们,然后通过引用将它们传递给函数。 在修改函数后执行此操作。