Jump to content

Archived

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

logged_with_bugmenot

How to use a global variable as the default value for a function parameter?

Recommended Posts

Here's an example script for what I'm trying to do:

[code]<?php
$current_ip = $_SERVER['REMOTE_ADDR'];

function get_resolved_ip($ip_address = $current_ip)
{
    return gethostbyaddr($ip_address);
}
$resolved_ip1 = get_resolved_ip('66.97.171.5'); // get the resolved address of 66.97.171.5
$resolved_ip2 = get_resolved_ip(); // get the resolved address of the current IP
?>[/code]

Normally I can find ways around this but doing it like this would be most efficient. To fix the above function:

[code]<?php
function get_resolved_ip($ip_address = '')
{
    global $current_ip;
    if($ip_address == '')
          $ip_address = $current_ip;
    return gethostbyaddr($ip_address);
}
?>[/code]

That's obviously a lot longer. Is there another way to use a global variable as a paramater default? Is my fixed function the best way to do it? Thx

Share this post


Link to post
Share on other sites

This is a bit more efficient:

[code]
function get_resolved_ip($ip_address = '')
{
    if($ip_address == '')
          $ip_address = $_SERVER['REMOTE_ADDR'];
    return gethostbyaddr($ip_address);
}
[/code]

Share this post


Link to post
Share on other sites
Thanks but, that was just an example function and other functions that I have written need to use a global variable which can't be generated inside the function. I guess I'm just disappointed that you can't use a variable as the default value for a parameter.

Share this post


Link to post
Share on other sites
You could do
[code]<?php
function get_resolved_ip($ip_address = '')
{
    $tmp = ($ip_address == '')?$_SERVER['REMOTE_ADDR']:$ip_address;
    return gethostbyaddr($tmp);
}
?>[/code]
or
[code]<?php
function get_resolved_ip($ip_address = '') {
      return(($ip_address != '')?gethostbyaddr($ip_address):gethostbyaddr($_SERVER['REMOTE_ADDR']));
}?>[/code]

Ken

Share this post


Link to post
Share on other sites

×

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.