根据当前命名空间动态使用不同的类

I would like my class to inherit methods off of its parent, I've done this by extending the class. But i would also like to instantiate a class using the basename(without namespace) and have the correct class be instantiate, chosen based on the current namespace and then fall back to a 'common' class if it doesn't exist.

example

<?php

namespace common\models {


    class Account extends Model{}
    class Orders extends Model{}

    class Customer extends Model{

        use common\models\Account;

        public static function getAccountClass(){
            echo get_class(new Account());
        }
        public static function getOrdersClass(){
            echo get_class(new Order());
        }
    }
}


namespace frontend\models {

    class Account extends common\models\Account {}

    class Customer extends common\models\customer {

    }
}

I would like the common\models\Customer::getAccountClass() to output common\models\Account

and

frontend\models\Customer::getAccountClass() to output frontend\models\Account

but as frontend\models\Orders doesn't exist frontend\models\Customer::getOrdersClass() will still output common\models\Orders

Did you try to use full namespace like this :

use common\models\Account as A2;
public static function getAccountClass(){
     echo get_class(new A2());
}

or

public static function getAccountClass(){
    echo get_class(new common\models\Account());
}

There is no "right" way to solve it. However you could do something like this

Add a component or a helper or even add it to the construct of your initial class( depends how much you need to use it ):

public static function getClass($class)
{
    if (class_exists('frontend' . '\\' . $class)) {
        return frontend . '\\' . $class;
    } else  {
        return $class;
    }
}

And then you just can do something like this

public static function getAccountClass(){
    return self::getClass(Account::class);
}