父文件夹中的phpʻuse`类 [英] php `use` class in parent folder

查看:58
本文介绍了父文件夹中的phpʻuse`类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用推进ORM nofollow> Composer ,但我无法创建新模型,因为PHP脚本与PHP类不在同一目录中。

I have installed Propel ORM with Composer but I cannot create a new model as the PHP script is not in the same directory as the PHP class.

我在 Test.php 内有类 Test 我想从 subfolder / index.php 使用它。请注意,类 Test 然后使用 Base / Test.php Base / Test c $ c>,因此在这里不能使用 require(),因为 Base / Test 可以继续使用作曲家生成的更多类。

I have class Test inside Test.php and I want to use it from subfolder/index.php. Note that class Test then uses Base/Test from Base/Test.php, so using require() is not an option here as Base/Test just goes on to use even more classes generated by composer.

传统上,我应该执行以下操作:

Traditionally, I'm supposed to do the following:

<?php
   use Test;
?>

但是由于我的父母有 Test 文件夹,我无法做到这一点,显然

but since I have Test in the parent folder, I cannot do that, and obviously

<?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

实际代码:
子文件夹/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
{

}


推荐答案

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

Test is a namespace and has literally nothing to do with folder structure. Namespaces have a folder-like structure, but you cannot use relative paths.

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

PSR-4 autoloaders, such as what most Composer packages use these days, map their namespaces in a way that very closely matches the folder structure, but they are still entirely separate concepts.

如果已声明文件中的名称空间,所有后续名称都被认为是相对于该路径的。例如:

If you have declared a namespace in a file all subsequent names are considered to be relative to that path. eg:

namespace Foo;

class Bar {}; // \Foo\Bar

如果要在外部使用 当前名称空间中的>,您需要声明完整路径,以 \ 开头,该路径表示 root 名称空间。例如:

If you want to use something outside of the current namespace you need to declare the full path, beginning with \ which signifies the root namespace. eg:

namespace Foo;
use \Test

class Bar { // \Foo\Bar
  public function test() {
    $test = new Test();
    $dbh = new \PDO();
  }
}

这篇关于父文件夹中的phpʻuse`类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆