Special Vars passed to a function??

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
malcolmboston
DevNet Resident
Posts: 1826
Joined: Tue Nov 18, 2003 1:09 pm
Location: Middlesbrough, UK

Special Vars passed to a function??

Post 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?
User avatar
Buddha443556
Forum Regular
Posts: 873
Joined: Fri Mar 19, 2004 1:51 pm

Post 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).
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post 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();
Post Reply