John
John

Reputation: 7880

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?

Upvotes: 0

Views: 131

Answers (4)

Wesley van Opdorp
Wesley van Opdorp

Reputation: 14941

The $data isn't in the same scope, that is why it's not available. If you want data available that are not defined within your class, you can pass the data along.

class Test 
{
    function __construct($data)
    {
        echo $data;
    }
}
$oTest = new Test('data');

Upvotes: 0

KingCrunch
KingCrunch

Reputation: 131881

I could suggest you to use globals, but thats quite ugly. I suggest you to use constants instead, as this feels sufficient

define('DATA', "Some Data");

Another solution is to inject the value into the object

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

Upvotes: 0

Adam Arold
Adam Arold

Reputation: 30528

The echo $data; tries to echo data from your local variable which is obviously not set. You should pass the $data to your constructor:

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

And it will work like this:

$test = new test($data);

You will have to initialize the global variable $data before instantiating the test object.

Upvotes: 0

&#211;lafur Waage
&#211;lafur Waage

Reputation: 70001

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");

Upvotes: 1

Related Questions