hairyhi Posted August 22, 2008 Share Posted August 22, 2008 Hi check out the following code: <?php include("config.php"); class A { private $x; function B() { echo $var1; } }; Alright in the above sample code.. the problem I m facing is: in case the variable var1 resides in config.php, I am not able to access it inside the function B of class A. This works on some versions of PHP, but not in the one i m using (5.2.6). One solution is to use a global keyword before var1, but I need a proper solution, like a case with a lot of vars. I cannot go on marking every var as global... Also there is a case where I need to use it in many functions, so I cannot also initialise it inside a function. Plz help. Link to comment https://forums.phpfreaks.com/topic/120917-using-php-include/ Share on other sites More sharing options...
Jibberish Posted August 22, 2008 Share Posted August 22, 2008 you could try somthing along the lines of include.php <?php class foo { $var1='hello' function getVar{ return this->var1; } } ?> index.php <?php include 'include.php'; class A { function B { $foo = new foo(); echo $foo->getVar1; } } ?> Link to comment https://forums.phpfreaks.com/topic/120917-using-php-include/#findComment-623312 Share on other sites More sharing options...
Ken2k7 Posted August 25, 2008 Share Posted August 25, 2008 What about this method: <?php require_once("config.php"); class A { private $x; function __construct ($x) { $this->x = $x; } function getX () { return $this->x; } } $woot = new A($var1); ?> Link to comment https://forums.phpfreaks.com/topic/120917-using-php-include/#findComment-624769 Share on other sites More sharing options...
aschk Posted August 26, 2008 Share Posted August 26, 2008 It really does depend on what var1 is... Is it a configuration setting for your whole application? If so it should probably be kep in a registry class of some sort, or alternatively made into a constant (so that it can be referenced). If, on the other hand, it's specific to class A then it should almost certainly be put into class A as a private/protected/public member variable... The choice is yours. Link to comment https://forums.phpfreaks.com/topic/120917-using-php-include/#findComment-625961 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.