命名空间适用于一个类,但不适用于其他类

时间:2018-07-25 23:35:12

标签: php namespaces

我正在研究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";
    }
}

sandbox / 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);
}

sandbox / 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),我也看不到任何错误。

在这方面请帮我,因为对两个班级都执行相同的步骤,使一个班级正常工作而另一个班级却使我发疯。

谢谢。

1 个答案:

答案 0 :(得分:1)

通过在使用bar或foo名称空间的页面顶部应用名称空间,它将定义名称空间并起作用。这样做:

namespace foo; #Or namespace bar; or whatever your namespace is.

您可以将其应用于需要使用该名称空间的任何页面。一个不错的教程是https://www.sitepoint.com/php-53-namespaces-basics/

相关问题