Search code examples
phpnamespacesphp-7

Namespaces and extended classes


I am new to namespaces and want to understand why my code does not work as expected. I've a base authentication class relying on a core model for users:

<?php
namespace Core\Auth;
use Core\Component;
use Core\Models\Users;

class Auth extends Component {
    public function __construct($options) {
        // do something
    }

    public function login($email, $password) {
        $user = Users::findByEmail($email);
        // do a lot more
    }
}

For a project using this core I have to modify the users model and therefor I extended the core authentication class:

<?php
namespace App\Auth;
use Core\Auth\Auth as Base;
use App\Models\Users;

class Auth extends Base {}

But when instantiating the class \App\Auth\Auth it seems to use \Core\Models\Users instead of \App\Models\Users. What is the problem?


Solution

  • Yes, indeed, you cannot override a namespace alias in another file.

    use statements only establish aliases. They don't load code or anything else.

    use Core\Models\Users;
    
    ...
    
    public function login($email, $password) {
        $user = Users::findByEmail($email);
    }
    

    This is exactly equivalent to:

    public function login($email, $password) {
        $user = \Core\Models\Users::findByEmail($email);
    }
    

    And use aliases are only valid within the file they're written in. You most certainly can't override another file's aliases. Otherwise you couldn't trust any code you write in any file due to the potential of name clashes, which is exactly what namespaces try to avoid.