Search code examples
phpclassscopeglobal-scope

How to access a global variable from within a class constructor


For example I have 3 files:

First index.php with following code :

<?php
  include("includes/vars.php");
  include("includes/test.class.php");

  $test = new test();
?>

then vars.php with following code:

<?php
  $data = "Some Data";
?>

and last test.class.php

 <?php
 class test 
{
  function __construct()
  {
    echo $data;
  }
}
?>

When I run index.php the Some Data value from $data variable is not displayed, how to make it to work?


Solution

  • Reading material.

    Because of scope. Data is within the global scope and the only thing available within a class are variables and methods within the class scope.

    You could do

    class test 
    {
      function __construct()
      {
        global $data;
        echo $data;
      }
    }
    

    But it is not good practice to use global variables within a class.

    You could pass the variable into the class via the constructor.

    class test 
    {
      function __construct($data)
      {
        echo $data;
      }
    }
    
    $test = new test("test");