everbright Posted June 4, 2009 Share Posted June 4, 2009 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? Link to comment https://forums.phpfreaks.com/topic/160864-could-not-retrieve-variable-using-global-in-class/ Share on other sites More sharing options...
Ken2k7 Posted June 4, 2009 Share Posted June 4, 2009 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); Link to comment https://forums.phpfreaks.com/topic/160864-could-not-retrieve-variable-using-global-in-class/#findComment-849026 Share on other sites More sharing options...
everbright Posted June 8, 2009 Author Share Posted June 8, 2009 Thanks Ken2k7 for the advice! I think I'll try that. Probably a good solution Link to comment https://forums.phpfreaks.com/topic/160864-could-not-retrieve-variable-using-global-in-class/#findComment-851636 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.