简体   繁体   中英

php: using extends with a class alias

I have classes in two different namespaces, for example:

Controller is in \\Core, Index is in \\Public

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.

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 {

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.

Edit: 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.

Thanks!

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

class Index extends \Public\Controller { }

\\ represents the root of your namespace.


Another way to do this is to use the use keyword

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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