Page 1 of 1

Special Vars passed to a function??

Posted: Tue Aug 03, 2004 8:03 am
by malcolmboston
ok, ive been having this problem for ages and no-one i have asked has been able to give me an answer

ok say we're defining a function, like so

Code: Select all

function get_time ()
{
$current_time = $time();
print $time;
}
now thats fine, but what if we needed to pass a $_POST, $_GET, $_SESSION, $_SERVER etc etc, i keep getting errors in syntax.

so if i tried to do this

Code: Select all

function get_time ($_POST['time'])
{
$current_time = $time();
print $time;
}
i am looking for someway of escaping but can find none

any help?

Posted: Tue Aug 03, 2004 9:32 am
by Buddha443556
That just isn't supported. Function arguments can be pass as values, references and a default scalar can be used. You can pass that value by either calling the function with it or accessing it from inside the function using globals (though not neccessary for your Superglobal example).

Posted: Tue Aug 03, 2004 10:02 am
by Weirdan
to pass $_GET element to function you have to write:

Code: Select all

function get_time($time) {
  echo $time;
}
get_time($_GET['time']);
to make the $_GET['time'] a default value for function argument:

Code: Select all

function get_time($time = false) {
  $time = $time ? $time : $_GET['time'];
  echo $time;
}
get_time();
$_GET, $_POST etc are superglobals, so you can use it in your function directly:

Code: Select all

function get_time() {
  echo $_GET['time'];
}
get_time();