peranha Posted February 28, 2009 Share Posted February 28, 2009 Is there a way to return a variable from a function inside a class? Ex. <?php // Function to retrieve user name. public function retrieve_username($userid) { $ruq = mysql_query("SELECT user_name FROM " . $this->pre . "users WHERE user_id = '{$userid}'"); $r = mysql_fetch_array($ruq) or die(mysql_error()); $username = $r[0]; return $username; } ?> Then I need to use the variable $username in another function. if I echo $username in the function, it will display "peranha", but if I echo $username on the page itself, it doesnt return anything. Quote Link to comment https://forums.phpfreaks.com/topic/147318-solved-oop-function-to-return-variable/ Share on other sites More sharing options...
corbin Posted February 28, 2009 Share Posted February 28, 2009 Methods that are not constructors can return values. The problem must be in your usage, or username is not set. Quote Link to comment https://forums.phpfreaks.com/topic/147318-solved-oop-function-to-return-variable/#findComment-773271 Share on other sites More sharing options...
peranha Posted February 28, 2009 Author Share Posted February 28, 2009 Here is my usage. <?php $profile->retrieve_username($userid); echo $username; ?> if I change the functio to <?php // Function to retrieve user name. public function retrieve_username($userid) { $ruq = mysql_query("SELECT user_name FROM " . $this->pre . "users WHERE user_id = '{$userid}'"); $r = mysql_fetch_array($ruq) or die(mysql_error()); $username = $r[0]; echo $username; } ?> "peranha" is outputted to the screen, so $username is set, just wont return with return $username. Am I not using it right? Quote Link to comment https://forums.phpfreaks.com/topic/147318-solved-oop-function-to-return-variable/#findComment-773277 Share on other sites More sharing options...
Daniel0 Posted February 28, 2009 Share Posted February 28, 2009 It returns a value just like all other methods/functions do. You need to store that return value somewhere, e.g. $username = $profile->retrieve_username($userid); echo $username; You need to lookup the word "scope" in the manual. Quote Link to comment https://forums.phpfreaks.com/topic/147318-solved-oop-function-to-return-variable/#findComment-773278 Share on other sites More sharing options...
peranha Posted February 28, 2009 Author Share Posted February 28, 2009 Thanks, cant believe I forgot to set the variable on the main page. Quote Link to comment https://forums.phpfreaks.com/topic/147318-solved-oop-function-to-return-variable/#findComment-773281 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.