a.schwab
a.schwab

Reputation: 261

Global Variables in static PHP classes

Is there a way to use a global variable everywhere in the code?

I want to use a Path variable to the located configured Folder in each Path I'll declare in my code.

Here's my Code: 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';
     }
?>

This won't work because it says, "Parse error: syntax error, unexpected T_VARIABLE" when I try to call $GLOBALS when declaring a static variable.

Is there a way to do this?

Thanks in Anticipation Alex

Upvotes: 1

Views: 6809

Answers (4)

Wesley van Opdorp
Wesley van Opdorp

Reputation: 14941

What you are looking for are constants.

It's very common to use them to define certain path's, f.e.

define('PATH_ROOT', $_SERVER['DOCUMENT_ROOT']);
define('PATH_TEMPLATES', PATH_ROOT.'/templates');

Upvotes: 2

Clement Herreman
Clement Herreman

Reputation: 10536

Tranform your (bad) public static attribute, to a public static getter/setter.

Also, global variables are a bad pratice, introducing side effect and name collision.

Upvotes: 0

Andri
Andri

Reputation: 1503

whenever you want to use a global variable inside a function that is out of the scope, you must first declare it within the function/class method with "global $varname".

In your case:

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';
          }
    }
?>

Upvotes: 0

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26719

Class constants and static class variables cannot be initialized with dynamic data.

What about defining method instead?

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

And why you would keep settings as global variables, and not encapsulate them in some kind of Registry?

Upvotes: 2

Related Questions