php: using extends with a class alias

2019-07-04 11:44发布

问题:

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!

回答1:

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 { }