Page 1 of 1

Global vars in a class.

Posted: Wed May 14, 2003 9:41 am
by V0oD0o
Hi all,

Is it possible to use global, pre-defined vars like $_SESSION["blahvar"] or $_SERVER["REQUEST_URI"] without actually *passing* them into the class itself?

As an example:

# Method
function cameFrom()
{
$this->cameFrom = urlencode($SERVER["HTTP_REFERER"]);
return $this->cameFrom;
} # End method

Thanks in advance,

Mike Pearce

Posted: Wed May 14, 2003 9:46 am
by volka
$_SESSION, $_SERVER and some more are super(or auto-)global arrays that can be accessed from anywhere.
http://www.php.net/manual/en/reserved.variables.php

Posted: Wed May 14, 2003 10:00 am
by V0oD0o
Thanks for the quick reply volka.

That's what I though, although that function doesn't return anything, neither does it return anything if I use REMOTE_ADDR.

If I do: $this->cameFrom = "testvarcontent"; it returns the string ok.

What could it be? I've been looking round the web and not found a thing.

Thanks,

Mike

Posted: Wed May 14, 2003 10:06 am
by volka
it's $_SERVER not $SERVER ;)
the only superglobal (if I'm not blind, which might be) without a leading _ is $GLOBALS.

Posted: Wed May 14, 2003 10:07 am
by McGruff
$_SERVER not $SERVER

Posted: Wed May 14, 2003 10:10 am
by V0oD0o
Thanks,

That was a typo in the post, in the actual class I have:

Code: Select all

function cameFrom()
        {
            $this->cameFrom = urlencode($_SERVERї"REQUEST_URI"]);
            #$this->cameFrom = urlencode($this->requestURI);
            return $this->cameFrom;
        } # End function

Posted: Wed May 14, 2003 10:13 am
by volka
which version of php do you use?
if you make it

Code: Select all

function cameFrom()
        {
            echo '<pre>'; print_r($_SERVER); echo '</pre>'; // debug only, do not forget to remove
            $this->cameFrom = urlencode($_SERVER["REQUEST_URI"]);
            #$this->cameFrom = urlencode($this->requestURI);
            return $this->cameFrom;
        } # End function
what does it print?

Posted: Thu May 15, 2003 3:51 am
by V0oD0o
Sorry for the delay!

I added that to my class and nothing was printed, the <pre> tags were, but nothing else.

Posted: Thu May 15, 2003 9:25 am
by V0oD0o
OK, it turns out that I've only got PHP 4.0.6.

Which is why $_SERVER wasn't working.

However, $HTTP_SERVER_VARS don't want to play ball when used in the class either.

Thanks for your help!

Posted: Thu May 15, 2003 9:33 am
by volka
$HTTP_SERVER_VARS is not superglobal. If you want to use it within the scope of a function or method you have to import the global scope for that variable

Code: Select all

function cameFrom()
        {
            global $HTTP_SERVER_VARS;
            echo '<pre>'; print_r($HTTP_SERVER_VARS); echo '</pre>'; // debug only, do not forget to remove
            $this->cameFrom = urlencode($HTTP_SERVER_VARS["REQUEST_URI"]);
            #$this->cameFrom = urlencode($this->requestURI);
            return $this->cameFrom;
        } # End function