php - 在 2 个单独的脚本中使用 PHP 命名空间声明是否正确?

标签 php namespaces

我正在学习 PHP 命名空间。我正在尝试向我编写的类添加命名空间,然后在另一个脚本中引用它。我是这样做的:

MenuBuilder.php

namespace Andytest\MenuBuilder;

class MenuBuilder {

    public function test() {
        echo 'testing';
    }
}

test.php (使用类的地方)
namespace Andytest\MenuBuilder;

require_once 'MenuBuilder.php';

$Builder = new MenuBuilder;
$Builder->test();

它的输出正如我所期望的 - 当我运行 test.php 时它会输出“testing”这个词。

但我不知道为什么我需要 namespace Andytest\MenuBuilder在 test.php 中,因为它已经在 MenuBuilder.php 中清除了,这是 test.php 所需要的?如果我删除 namespace在 test.php 行它不起作用。

我这样做正确吗?

最佳答案

test.php你应该有 use Andytest\MenuBuilder\MenuBuilder;而不是 namespace Andytest\MenuBuilder;
因为你用的是namespace而不是 use该文件需要您创建的每个未在 use 中指定的类大小写在同一个命名空间中,因此 new MenuBuilder();实际调用new Andytest\MenuBuilder\MenuBuilder(); .

如果您要更改 namespacetest.php它应该告诉你它找不到MenuBuilder

关于php - 在 2 个单独的脚本中使用 PHP 命名空间声明是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39506575/

相关文章:

xml - SOAP 响应的命名空间不适用于 XPath

visual-c++ - "using namespace ...."为什么?

java - Java 项目中嵌入 BaseX 的 "No namespace declared for bin:bin"错误

php - Magento 产品分类

PHP 使用条件 if/elseif/else 创建 MySQL 查询

java - 我应该在 Solr(或任何数据库)中索引或存储这些字段吗?

namespaces - SASS:如何将样式表中的每个规则与选择器一起添加到 'namespace'

ruby-on-rails - Rails 通过缺少列命名空间 has_many

php - 仅在插件页面 WordPress 上显示样式表

PHP 析构函数 | unset() VS 覆盖对象