php:使用具有类别名的extends [英] php: using extends with a class alias

查看:110
本文介绍了php:使用具有类别名的extends的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在两个不同的命名空间中有类,例如:

I have classes in two different namespaces, for example:

控制器位于\ Core中, 索引位于\ Public

Controller is in \Core, Index is in \Public

在我的index.php中,我具有所有\ Core类的class_alias,因此您可以直接调用它们:$controller = new Controller();.这没有问题.

In my index.php, I have a class_alias for all of the \Core classes, so you can call them directly: $controller = new Controller();. This works without issue.

我的问题是当我尝试扩展课程时.自索引和Controller在不同的名称空间中,它尝试在\ Public名称空间中查找Controller,所以这不起作用:

My problem is when I try to extend the class. Since Index & Controller are in different namespaces, it tries to find Controller in the \Public namespace so this doesn't work:

<?php
namespace Panel\Pub;

class Index extends Controller {

有没有解决的办法,所以我可以在extends函数中使用类别名?我知道我可以使用\ Core \ Controller,并且可以使用,但是我正在尝试使用别名使核心功能更易于访问.

Is there any way around this so I can use the class alias in the extends function? I know I can use \Core\Controller and it will work, but I'm trying to use aliases to make core functions more easily accessible.

修改:找到了一种解决方法 经过更多测试之后,我发现在扩展名的别名前面使用\似乎可以正常工作.不如没有\理想,但目前最好的解决方案是:

Found one workaround After doing some more testing, I found that using \ in front of the alias in the extend seems to work. Not as ideal as no \ but currently the best solution results in:

class Index extends \Controller { }

仍在寻找其他解决方法或扩展控制器的其他方法.

Still looking for other advice on a work around or different method of extending controller.

谢谢!

推荐答案

使用名称空间时,将使用名称空间中的完整路径

When you're using a namespace, you use the full path in your namespace

class Index extends \Public\Controller { }

\代表名称空间的根.

另一种方法是使用use关键字

Another way to do this is to use the use keyword

namespace Panel\Pub;
use \Public\Controller as Controller
class Index extends Controller { }

这篇关于php:使用具有类别名的extends的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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