使libphonenumber与autoloader.php一起使用时出现问题

时间:2018-12-18 15:21:15

标签: php libphonenumber

美好的一天,

通过将autoloader.php与spl_autoload_register结合使用,我无法使用libphonenumber框架。 我没有使用作曲家,而是想使用PSR4自动加载器。

我尝试了一些在这里和其他地方找到的示例,但没有成功。

例如: 我的脚本路径:/opt/lampp/htdocs/project/incl/register.php

框架路径:/ opt / lampp / htdocs / project / incl / libphonenumber

在autoloader.php中

<?php
spl_autoload_register(function($class) {
  $prefix = 'libphonenumber'; // namespace prefix
  $base_dir = __DIR__.DIRECTORY_SEPARATOR.$prefix.DIRECTORY_SEPARATOR; // base directory for the namespace prefix

echo 'base-dir: ', var_dump($base_dir), '<br>';
echo 'class: ', var_dump($class), '<br>';

  // does the class use the namespace prefix?
  $len = strlen($prefix);

echo 'strncmp: ', var_dump(strncmp($prefix, $class, strlen($prefix))), '<br>';
echo 'relative class: ', var_dump(substr($class, strlen($prefix))), '<br>';

  if (strncmp($prefix, $class, $len) !== 0) {  // using this on "PhoneNumberUtil" doesn't make sense
    return; // no, move to the next registered autoloader
  }

  // get the relative class name
  $relative_class = substr($class, $len);  // using this on "PhoneNumberUtil" doesn't make sense

  // replace the namespace prefix with the base directory, replace namespace separators with directory separators in the relative class name, append with .php
  // $file = $base_dir.str_replace('\\', '/', $relative_class).'.php';
echo 'file with relative-class: ', var_dump($base_dir.str_replace('\\', '/', $relative_class).'.php'), '<br>';
  $file = $base_dir.str_replace('\\', '/', $class).'.php';
echo 'file: ', var_dump($file), '<br>';

  // if the file exists, require it
  if (file_exists($file)) { require_once $file; }
});

结果:

base-dir:字符串(46)“ / opt / lampp / htdocs / project / incl / libphonenumber /”

class:字符串(15)“ PhoneNumberUtil”

strncmp:int(1)

相对类别:字符串(1)“ l”

具有相对类别的文件:字符串(51)“ /opt/lampp/htdocs/project/incl/libphonenumber/l.php”

文件:字符串(65)“ /opt/lampp/htdocs/project/incl/libphonenumber/PhoneNumberUtil.php”

PhoneNumberUtil.php在最后一行加载。

register.php中的代码:

include_once 'autoloader.php';

$phone_util = PhoneNumberUtil::getInstance();

结果:

致命错误:在/opt/lampp/htdocs/project/incl/register.php中找不到类'PhoneNumberUtil'

尝试了另一个autoloader.php:

<?php
spl_autoload_register(function($className) {
  include __DIR__.'/libphonenumber/'.str_replace('\\', DIRECTORY_SEPARATOR, $className).'.php';
});

相同的结果:

致命错误:在/opt/lampp/htdocs/project/incl/register.php中找不到类'PhoneNumberUtil'

有人可以告诉我我在做什么错吗?

编辑

更多信息:

我想使用https://github.com/giggsey/libphonenumber-for-php中的libphonenumber软件包

我尝试按照此处显示的autoloader.php示例进行操作,但没有成功。

按照我发现的示例,我的代码应该可以,但是不能。

我试图找到更多解释,但没有帮助。

不幸的是,我仍然无法理解为什么我的代码无法正常工作。

谢谢。

1 个答案:

答案 0 :(得分:-1)

没关系。

我是通过反复试验自己找到解决方案的。

通过更改此内容:

$phone_util = PhoneNumberUtil::getInstance();

在register.php中:

$phone_util = libphonenumber\PhoneNumberUtil::getInstance();

工作正常。

但是,我无法从逻辑上解释为什么需要额外的代码。

在我看来,这似乎是PHP中的错误。

我认为应该在autoloader.php中进行处理。