父文件夹中的php`use`类

问题描述 投票:1回答:1

我已经使用Propel ORM安装了Composer,但我无法创建新模型,因为PHP脚本与PHP类不在同一目录中。

我在Test里面有类Test.php,我想从subfolder/index.php使用它。请注意,类Test然后使用来自Base/TestBase/Test.php,因此使用require()不是一个选项,因为Base/Test只是继续使用由composer生成的更多类。

传统上,我应该做以下事情:

<?php
   use Test;
?>

但由于我在父文件夹中有Test,我不能这样做,显然

<?php
   use ../Test;
?>

不起作用。

我的文件夹结构:

My Project
|-- Base
|   `-- Test.php <-- File referenced by `Test` class
|-- subfolder
|   `-- index.php <-- File I want to use `Test` from
`-- Test.php <-- File containing `Test` class

实际代码:subfolder/index.php

<?php 
use \Test;
    require __DIR__ . '/../vendor/autoload.php';
    $test = new Test();
?>

Test.php

<?php
use Base\Test as BaseTest;

class Test extends BaseTest
{

}
php namespaces composer-php propel
1个回答
3
投票

Test是一个名称空间,与文件夹结构完全无关。命名空间具有类似文件夹的结构,但您不能使用相对路径。

PSR-4自动加载器,例如目前大多数Composer软件包使用的,以与文件夹结构非常匹配的方式映射其命名空间,但它们仍然是完全独立的概念。

如果已在文件中声明了命名空间,则所有后续名称都被视为相对于该路径。例如:

namespace Foo;

class Bar {}; // \Foo\Bar

如果要使用当前命名空间之外的东西,则需要声明完整路径,从\开始,它表示根命名空间。例如:

namespace Foo;
use \Test

class Bar { // \Foo\Bar
  public function test() {
    $test = new Test();
    $dbh = new \PDO();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.