0

コード内のどこでもグローバル変数を使用する方法はありますか?

コードで宣言する各パスにある構成済みフォルダーへのパス変数を使用したいと思います。

これが私のコードです:Index.php

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

Common.php

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

Path.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」を使用して関数/クラスメソッド内で宣言する必要があります。

あなたの場合:

Common.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.
?>

Path.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

(悪い)publicstatic属性をpublicstatic getter/setterに変換します。

また、グローバル変数は悪い習慣であり、副作用と名前の衝突を引き起こします。

于 2011-08-23T08:20:10.790 に答える