PHP命名空间的奇怪问题

时间:2014-05-12 10:16:00

标签: php namespaces runtime-error

我打了一个测试PHP脚本。它会输出一些远程连接的基于地理IP的数据。没什么特别的,只是一个快速的原型。

但我看到一种奇怪的行为,所以我在这里问是否有人有任何关于它的线索。 PHP是Ubuntu 64位上的5.5.12版本。

以下是geoip_test.php调用脚本中的一些代码:

require_once ('geoip_utils.php');

$server_geoip_record = geoip_record_by_name('php.net');
echo '<pre>PHP.net web server location: ' . print_r($server_geoip_record, 1);
echo '<br />PHP.net web server local time: ' . \df_library\getUserTime($server_geoip_record)->format('Y-m-d H:i:s');

没什么好看的,不是吗?

现在简单的geoip_utils.php代码:

<?php

namespace df_library;

require_once('timezone.php');

// Given an IP address, returns the language code (i.e. en)
function getLanguageCodeFromIP($input_ip)
{

};

// Given a geo_ip_record, it returns the local time for the location indicated
// by it. In case of errors, it will return the optionally provided fall back value
function getUserTime($geoip_record, $fall_back_time_zone = 'America/Los_Angeles') {
    //Calculate the timezone and local time
    try
    {
        //Create timezone
        $timezone = @get_time_zone($geoip_record['country_code'], ($geoip_record['region'] != '') ? $geoip_record['region'] : 0);

        if (!isset($timezone)) {
            $timezone = $fall_back_time_zone;
        }

        $user_timezone = new \DateTimeZone($timezone);

        //Create local time
        $user_localtime = new \DateTime("now", $user_timezone);       
    }
    //Timezone and/or local time detection failed
    catch(Exception $e)
    {
        $user_localtime = new \DateTime("now");
    }

    return $user_localtime;
}

?>

当我运行调用脚本时,我得到:

PHP Fatal error:  Call to undefined function df_library\getUserTime() in /var/www/apps/res/geoip_test.php on line 5

有趣的是:如果我添加这个调试代码:

$x = get_defined_functions();
print_r($x["user"]);

我得到了这个输出:

Array
(
    [0] => df_library\getlanguagecodefromip
    [1] => df_library\gettimezone
    [2] => df_library\getutcdatetime
    [3] => df_library\getlocalizedtime
    [4] => df_library\getutcdatetimeaslocalizeddatetime
    [5] => df_library\getlocalizeddatetimeasutcdatetime
    [6] => get_time_zone
)

首先,我不明白为什么函数名称被转换为小写。 但最重要的是,请注意索引0如何显示正在定义的空函数函数getLanguageCodeFromIP($input_ip),并且该函数正好位于解释器抱怨未定义的函数之上! 为什么PHP会看到该文件中的其他函数,而不是我想要使用的函数?

欢迎任何想法!

1 个答案:

答案 0 :(得分:1)

在函数;的右括号后面有一个额外的分号getLanguageCodeFromIP,导致PHP解析器无法识别getLanguageCodeFromIP之后的函数。

正如OP的评论所证明的那样,删除;解决了问题。

相关问题