0

有没有办法在代码中的任何地方使用全局变量?

我想在我将在我的代码中声明的每个路径中使用一个路径变量来定位配置的文件夹。

这是我的代码:Index.php

<?php
     require_once('Common.php');
     require_once('Path.php');
?>

通用.php

<?php 
     $RootPath = '.';//in this case its root
     //add the RootPath for global using
     $GLOBALS['RootPath'] = $RootPath;
?>

路径.php

<?php
     class Path {
          public static $TemplatePath = $GLOBALS['RootPath'].'/Template.php';
     }
?>

这不起作用,因为当我在声明静态变量时尝试调用 $GLOBALS 时,它会显示“解析错误:语法错误,意外的 T_VARIABLE”。

有没有办法做到这一点?

感谢期待亚历克斯

4

4 回答 4

2

您正在寻找的是常量

使用它们来定义某些路径是很常见的,fe

define('PATH_ROOT', $_SERVER['DOCUMENT_ROOT']);
define('PATH_TEMPLATES', PATH_ROOT.'/templates');
于 2011-08-23T08:43:10.913 回答
1

类常量和静态类变量不能用动态数据初始化。

那么定义方法呢?

 class Path {
          public static getTemplatePath()
          {
            return $GLOBALS['RootPath'].'/Template.php';
          }
     }

为什么要将设置保留为全局变量,而不是将它们封装在某种注册表中?

于 2011-08-23T08:18:43.173 回答
0

每当您想在超出范围的函数中使用全局变量时,您必须首先在函数/类方法中使用“global $varname”声明它。

在你的情况下:

通用.php

<?php 
     $RootPath = '.';//in this case its root
     //add the RootPath for global using
     // $GLOBALS['RootPath'] = $RootPath; // no need for this, $[GLOBALS] is about the Superglobals, $_SERVER, $_SESSION, $_GET, $_POST and so on, not for global variables.
?>

路径.php

<?php
     class Path {
          public static $TemplatePath;// = $GLOBALS['RootPath'].'/Template.php';

          public method __construct(){
               global $RootPath;
               self::TemplatePath =  $RootPath.'/Template.php';
          }
    }
?>
于 2011-08-23T08:20:04.660 回答
0

将您的(坏的)公共静态属性转换为公共静态 getter/setter。

此外,全局变量是一种不好的做法,会引入副作用和名称冲突。

于 2011-08-23T08:20:10.790 回答