Jump to content

How to reference a variable within a function within a class?


jdlev

Recommended Posts

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>";

?>

 

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.

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;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.