我正在开发一个 PHP 项目,我仍在学习如何将命名空间应用于它。我想出了以下情况:
文件结构是
app.php
index.php
bar.php
sandbox
\_index.php
\_Foo.class.php
文件内容如下:
app.php
<?php
function strtocapital($string)
{
return substr(strtolower($string), 0, strrpos($string, '/')) . substr(strtoupper($string), strrpos($string, '/'), 2) . substr(strtolower($string), strrpos($string, '/') + 2);
}
function autoloader($className)
{
$path = __DIR__ . '/' . strtolower($className) . '.php';
if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
$className = str_replace('\\', '/', $className);
$path = __DIR__ . '/' . strtolower($className) . '.php';
}
if (!is_file($path)) {
$className = strtocapital($className);
$path = __DIR__ . '/' . $className . '.class.php';
if (!is_file($path)) {
return false;
}
}
include_once $path;
echo "Successfully loaded ${className}<br>";
}
spl_autoload_register("autoloader");
index.php
<?php
require 'app.php';
use Sandbox\Foo as Fuu;
echo __DIR__ . '<br>';
$foo = new Fuu();
try {
echo $foo::FOOFOO;
$foo::foofoofoo();
} catch (Exception $e) {
print_r($e);
}
bar.php
<?php
class Bar
{
const BARBAR = "dada";
public static function barbarbar()
{
echo "Bar bar bar";
}
}
沙箱/index.php
<?php
require '../app.php';
use Bar;
echo __DIR__ . '<br>';
$bar = new Bar();
try {
echo $bar::BARBAR;
$bar::barbarbar();
} catch (Exception $e) {
print_r($e);
}
沙箱/Foo.class.php
<?php
class Foo
{
const FOOFOO = "bla";
public static function foofoofoo()
{
echo "Foo foo foo";
}
}
尽管我收到了两条成功的消息:
Successfully loaded Sandbox\Foo
Successfully loaded Bar
我只看到 Bar 类的输出。它们的区别在于
sandbox/index.php
返回 HTTP 状态 200 和 index.php
返回 HTTP 状态 500。但是,即使在尝试 error_reporting(E_ALL)
之后,我也没有看到任何错误。 .请帮我解决这个问题,因为对两个类都执行相同的步骤并且让一个工作而另一个不工作让我发疯。
提前致谢。
最佳答案
通过在使用 bar 或 foo 命名空间的页面顶部应用命名空间,它将定义命名空间并工作。这样做:
namespace foo; #Or namespace bar; or whatever your namespace is.
您可以将其应用于需要使用该命名空间的任何页面。一个很好的教程是 https://www.sitepoint.com/php-53-namespaces-basics/ .
关于php - 命名空间适用于一个类,但不适用于其他类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51529069/