Jump to content


Photo

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


  • Please log in to reply
3 replies to this topic

#1 logged_with_bugmenot

logged_with_bugmenot
  • Members
  • PipPipPip
  • Advanced Member
  • 62 posts

Posted 08 August 2006 - 04:26 PM

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

<?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
?>

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

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

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
Earn money with Google AdSense

#2 bltesar

bltesar
  • Members
  • PipPipPip
  • Advanced Member
  • 109 posts

Posted 08 August 2006 - 05:08 PM


This is a bit more efficient:

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


#3 logged_with_bugmenot

logged_with_bugmenot
  • Members
  • PipPipPip
  • Advanced Member
  • 62 posts

Posted 08 August 2006 - 05:11 PM

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.
Earn money with Google AdSense

#4 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 08 August 2006 - 05:19 PM

You could do
<?php
function get_resolved_ip($ip_address = '')
{
     $tmp = ($ip_address == '')?$_SERVER['REMOTE_ADDR']:$ip_address;
     return gethostbyaddr($tmp);
}
?>
or
<?php
function get_resolved_ip($ip_address = '') {
      return(($ip_address != '')?gethostbyaddr($ip_address):gethostbyaddr($_SERVER['REMOTE_ADDR']));
}?>

Ken




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users