简体   繁体   English

PHP:在命名空间中使用外部 class

[英]PHP: Use external class in a namespace

There is a class which handles the internationalization.有一个处理国际化的 class 。

<?php

class Language{
    // ...
}

Now I created a renderer.php file which should handle all injections for HTML.现在我创建了一个renderer.php文件,它应该处理 HTML 的所有注入。

<?php
namespace Renderer;

include_once '../language.php';

function drawUserList(){
    // ...
    $group = Language::translate($groupName);
   // ...
}

In this file I need my Language class.在这个文件中,我需要我的Language class。 But my compiler throws the following error message:但是我的编译器会抛出以下错误消息:

Undefined type 'Renderer\Language'.

The Language class is not part of a namespace. Language class 不是命名空间的一部分。 Why adds PHP a namespace to it?为什么要向它添加 PHP 命名空间? And why I am not able to use the class in my namespace function?为什么我不能在我的命名空间 function 中使用 class?

PHP Version 7.4.26 PHP 版本 7.4.26

You have to use the keywork use :您必须使用 keywork use

namespace Renderer;
use Language; // indicate to use \Language

include_once '../language.php';

function drawUserList(){
    // ...
    $group = Language::translate($groupName);
   // ...
}

or use $group = \Language::translate() .或使用$group = \Language::translate()

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

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