logged_with_bugmenot Posted August 8, 2006 Share Posted August 8, 2006 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 https://forums.phpfreaks.com/topic/16914-how-to-use-a-global-variable-as-the-default-value-for-a-function-parameter/ Share on other sites More sharing options...
bltesar Posted August 8, 2006 Share Posted August 8, 2006 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] Link to comment https://forums.phpfreaks.com/topic/16914-how-to-use-a-global-variable-as-the-default-value-for-a-function-parameter/#findComment-71240 Share on other sites More sharing options...
logged_with_bugmenot Posted August 8, 2006 Author Share Posted August 8, 2006 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. Link to comment https://forums.phpfreaks.com/topic/16914-how-to-use-a-global-variable-as-the-default-value-for-a-function-parameter/#findComment-71241 Share on other sites More sharing options...
kenrbnsn Posted August 8, 2006 Share Posted August 8, 2006 You could do[code]<?phpfunction get_resolved_ip($ip_address = ''){ $tmp = ($ip_address == '')?$_SERVER['REMOTE_ADDR']:$ip_address; return gethostbyaddr($tmp);}?>[/code]or[code]<?phpfunction get_resolved_ip($ip_address = '') { return(($ip_address != '')?gethostbyaddr($ip_address):gethostbyaddr($_SERVER['REMOTE_ADDR']));}?>[/code]Ken Link to comment https://forums.phpfreaks.com/topic/16914-how-to-use-a-global-variable-as-the-default-value-for-a-function-parameter/#findComment-71246 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.