jdlev Posted June 27, 2013 Share Posted June 27, 2013 Let's say I wanted to pull the host & address variables out of the function "ip" and echo them outside of the class. How would I go about doing that? I tried in the code below and failed miserably <?php //Returns information on the User's IP Address, Hostname, Port, and Username class getIP { public function ip() { $this->address = $_SERVER['REMOTE_ADDR']; $this->host = $_SERVER['REMOTE_HOST']; } } $addy = new getEm; echo $addy->ip(this->address) . "</br>"; ?> Quote Link to comment https://forums.phpfreaks.com/topic/279637-how-to-reference-a-variable-within-a-function-within-a-class/ Share on other sites More sharing options...
ginerjm Posted June 27, 2013 Share Posted June 27, 2013 Most class design articles tell you that you should setup functions to "get" and "set" class-based vars. So - sounds like you simply need a function that returns the values you want. And then you echo them. Quote Link to comment https://forums.phpfreaks.com/topic/279637-how-to-reference-a-variable-within-a-function-within-a-class/#findComment-1438222 Share on other sites More sharing options...
jdlev Posted June 27, 2013 Author Share Posted June 27, 2013 So you can't call multiple variables from a function within a class? You need to make a function for each variable you want, and just call the function itself? Quote Link to comment https://forums.phpfreaks.com/topic/279637-how-to-reference-a-variable-within-a-function-within-a-class/#findComment-1438223 Share on other sites More sharing options...
Solution AbraCadaver Posted June 27, 2013 Solution Share Posted June 27, 2013 (edited) Well your function is setting the class vars so you need to call the function and then echo the vars. $addy = new getIP; $addy->ip(); echo $addy->address; Not sure of your intent but probably more like this to set on instantiation: class getIP { private $address = ''; private $host = ''; function __construct() { $this->address = $_SERVER['REMOTE_ADDR']; $this->host = $_SERVER['REMOTE_HOST']; } function __get($var) { return $this->{$var}; } } $addy = new getIP; echo $addy->address; Edited June 27, 2013 by AbraCadaver Quote Link to comment https://forums.phpfreaks.com/topic/279637-how-to-reference-a-variable-within-a-function-within-a-class/#findComment-1438228 Share on other sites More sharing options...
jdlev Posted June 27, 2013 Author Share Posted June 27, 2013 I'm a dumbass. I can't believe I couldn't figure that out. Thanks for the help, I appreciate it Quote Link to comment https://forums.phpfreaks.com/topic/279637-how-to-reference-a-variable-within-a-function-within-a-class/#findComment-1438238 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.