Don'tDownvoteMe
Don'tDownvoteMe

Reputation: 511

How to use namespaces in case of inheritance?

I am new to OOPS thus want to clarify things. I have this code below which works perfectly fine.

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;

class AdminController extends Controller
{
    public function index()
    {
        echo "admin controller";
    }

}

Now I don't intend to use use keyword as it is going to be used once also wanted to experiment and thus, I used the code below.

namespace App\Http\Controllers\Admin;

class AdminController extends App\Http\Controllers\Controller
{
    public function index()
    {
        echo "admin controller";
    }

}

Now the above mentioned code without use keyword throws a fatal error exception. Why does that happen? In theory,I think I am doing exactly what is supposed to be done then why the exception?

Upvotes: 2

Views: 63

Answers (1)

Rahman Qaiser
Rahman Qaiser

Reputation: 682

You will have to import it from global namespace , below code will work fine

namespace App\Http\Controllers\Admin;

class AdminController extends \App\Http\Controllers\Controller
{
    public function index()
    {
        echo "admin controller";
    }

}

Use keyword import class from global namespace, but

class AdminController extends App\Http\Controllers\Controller

it will import parent class relative you current namespace (namespace App\Http\Controllers\Admin) , so translated path will be: App\Http\Controllers\Admin\App\Http\Controllers\Controller which is invalid.

Upvotes: 3

Related Questions