ChadNomad Posted December 21, 2007 Share Posted December 21, 2007 How do you use a variable outside a class? I've included a class on a page and I want to echo a string made within a function. Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/82717-solved-using-function-variables-outside-a-class/ Share on other sites More sharing options...
p2grace Posted December 21, 2007 Share Posted December 21, 2007 If by this you mean you've declared a variable that you want to use inside of a class you do the following. $var = "sample"; class testClass { public function grabGlobalVar(){ global $var; echo $var; // will result in "sample" } } Quote Link to comment https://forums.phpfreaks.com/topic/82717-solved-using-function-variables-outside-a-class/#findComment-420758 Share on other sites More sharing options...
ChadNomad Posted December 21, 2007 Author Share Posted December 21, 2007 Heres the setup. Maybe this will make more sense. I'm trying to use a variable from a function inside a class and use that in a completely different page where the class file is included. login.class.php class Login() { function ProcessLogin($username, $password) { $this->MyVar = "Hello"; } } $login = new Login(); $login->ProcessLogin($username, $password) login.php include("login.class.php"); echo $login->MyVar; // <- This is my problem. Doesn;t work... I've tried using "global" to no avail... Quote Link to comment https://forums.phpfreaks.com/topic/82717-solved-using-function-variables-outside-a-class/#findComment-420765 Share on other sites More sharing options...
papaface Posted December 21, 2007 Share Posted December 21, 2007 Use: class Login() { var MyVar; function ProcessLogin($username, $password) { $this->MyVar = "Hello"; } } $login = new Login(); $login->ProcessLogin($username, $password) Then try: include("login.class.php"); echo $login->MyVar; Quote Link to comment https://forums.phpfreaks.com/topic/82717-solved-using-function-variables-outside-a-class/#findComment-420767 Share on other sites More sharing options...
emehrkay Posted December 21, 2007 Share Posted December 21, 2007 try instantiating the Login() class on login.php what version of php are you running? maybe you should declare your class properties first class Login(){ var $MyVar; //php4 public $MyVar;//php5 ... } Quote Link to comment https://forums.phpfreaks.com/topic/82717-solved-using-function-variables-outside-a-class/#findComment-420769 Share on other sites More sharing options...
ChadNomad Posted December 21, 2007 Author Share Posted December 21, 2007 Haha I'm an idiot. Nevermind! Thanks, all your suggestions worked it was me being stupid. Quote Link to comment https://forums.phpfreaks.com/topic/82717-solved-using-function-variables-outside-a-class/#findComment-420775 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.