简体   繁体   English

在类方法中使用php中命名空间中的类

[英]use class from namespace in php in class method

I'm new to php and trying to use namespace s for the first time and I have this crazy problem in a big php file (simplified below): 我是php的新手,第一次尝试使用namespace s,我在一个大的php文件(以下简化)中遇到了这个疯狂的问题:

B.php: B.php:

namespace Logic;

class C {}
class B {}

A.php: A.php:

use Logic\C;

class A extends \BaseClass {
    public function __construct() {}
    // [...500 lines of code...]
    private function hi() { $c = new C(); }
}

The hi method gives the error: Class 'Logic\\\\C' not found in A.php hi方法给出错误: Class 'Logic\\\\C' not found in A.php


But if I just reference B in the constructor of A, it works as expected: 但是,如果我只是在A的构造函数中引用B,它将按预期工作:

class A extends \Base {
    public function __construct() { $dummy = new C(); }
    // [...500 lines of code...]
    private function hi() { $c = new C(); }
}

When the hi method in the modified code above is run, there are no problems. 当运行上面修改后的代码中的hi方法时,没有问题。

Can anybody think of a reasonable explanation for why this happens? 谁能想到一个合理的解释为什么会这样? Am I misusing namespaces in php? 我在php中滥用名称空间吗?

You need to understand, that the use statement doesn't automatically include the source code file where Logic\\C is defined. 您需要了解, use语句不会自动包含定义Logic\\C的源代码文件。 You need to use an autoloader, or manually require_once that file before accessing classes from that file. 您需要手动使用自动加载磁带机,或require_once从该文件访问类之前该文件。


I suggest to follow the manual about namespaces (and the examples there): http://php.net/manual/en/language.namespaces.php 我建议遵循有关名称空间的手册(及其中的示例): http : //php.net/manual/zh/language.namespaces.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM