我应该如何调用这个函数? PHP

How should I call this function? PHP

我该如何调用这个函数?我是 PHP 的新手。这是我的代码...但我有一个错误

Notice: Undefined variable: ip in C:\xampp\htdocs\PHPTest\ip.php on line 19

    <?php
    function getRealIpAddr(){
        if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
        {
          $ip=$_SERVER['HTTP_CLIENT_IP'];
        }
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
        {
          $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        else
        {
          $ip=$_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }
    call_user_func('getRealIpAddr', '$ip');
    echo $ip;
    ?>

更新

Strange reason, I'm using Windows 10, localhost, xampp and google Chrome this script doesn't provide me an ip address! That's why a corrected code was empty... Thought it was some kind of errors or something

第二次更新

If you're getting no ip like me, you may try this solution

您无法访问在函数内声明的变量,但您可以使用 return 语句:

echo getRealIpAddr();

而不是:

call_user_func('getRealIpAddr', '$ip');
echo $ip;

您的函数 return 是 IP 地址,因此将变量分配给函数的 return 值,如下所示:

$ip = getRealIpAddr();

错误很明显$ip未定义:

修改后的代码:

<?
function getRealIpAddr(){
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
        $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
        $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
        $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

$ip = getRealIpAddr(); // your function
echo $ip;
?>

如果您想使用在函数内部定义的 $ip 变量,请注意 $ip 的范围仅限于函数。

你不能在函数外调用这个变量。为此,您需要将它存储在一个变量中,如上面提到的示例 ($ip = getRealIpAddr();).