Jump to content

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
Link to comment
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
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.