开发者

Php problem with variables

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 i开发者_开发问答ndex.php the Some Data value from $data variable is not displayed, how to make it to work?


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


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜