Jump to content

Could not retrieve variable using global in class


everbright

Recommended Posts

Hi all,

 

I'm using PHP v5.2.9. Am having some problem with variable scoping here, as follows:

 

I have a file config.php as follows. Basically this defines a list of configuration parameters to be used by a class.

 

config.php

$config1 = 'Test1';

$config2 = 'Test2';

 

Then I have another file class.php in the same folder, which includes config.php and tries to use the configuration parameter as follows:

 

class.php

require_once 'config.php';

class TestClass {

    function testConfig() {

        global $config1, $config2;

        print "Config 1 = $config1, Config 2 = $config2";

    }

}

 

When I tried to create the class and run testConfig, the 2 config variables are empty, i.e. could not get the values from config.php.

 

One solution will be to pull the configuration parameters inline to class.php, but I want to avoid that, as the configurations will be used elsewhere and I want to avoid duplication of code.

 

Has anyone encountered such a problem also? Any suggestions on what I can do to work around this?

 

I would say no to globals. I would just add them to the class via the constructor.

 

<?php
require_once 'config.php';
class TestClass {
     private $config1;
     private $config2;
     public function __construct ($config1, $config2) {
          $this->config1 = $config1;
          $this->config2 = $config2;
     }
     public function testConfig () {
          echo sprintf("Config 1 = %s, Config 2 = %s", $this->config1, $this->config2);
     }
}

$testclass = new TestClass($config1, $config2);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.