php中的类替换

igo*_*gor 8 php oop constructor class

有没有办法使它工作?见例子:

class car {
        function __construct($type){
                switch ($type) {
                        case 'big' : return new big_car();
                        case 'small' : return new small_car();
                }
        }
        function whatisit () {
                echo "this is car ;( \n";
        }
}

class big_car extends car {
        function __construct(){}
        function whatisit () {
                echo "this is big car ;) \n";
        }
}

class small_car extends car {
        function __construct(){}
        function whatisit () {
                echo "this is small car ;) \n";
        }
}
Run Code Online (Sandbox Code Playgroud)

所以目标是以这种方式使用它:

$mycar = new car('big');
$mycar->whatisit(); // i want it to say that it's big
Run Code Online (Sandbox Code Playgroud)

我非常想它的方法不好而且不能这样工作,但也许有一招?

PS ::我知道我可以使用特殊的静态方法,但......

Ja͢*_*͢ck 9

你需要一家汽车厂来制造新车; 这不是JavaScript :)

class car_factory 
{
    function create_car($type = null) 
    {
        switch ($type) {
             case 'big':
                 return new big_car();

             case 'small':
                 return new small_car();

             case null:
                 return new car();
        }
        throw new InvalidArgumentException($type);
    }
}

$factory = new car_factory;
$small_car = $factory->create_car('small');
$std_car = $factory->create_car();
Run Code Online (Sandbox Code Playgroud)

当然,您应该__construct从原始代码中删除该功能.

正如评论中所提到的,你可以通过使用动态类来完全概括这一点,假设类扩展具有相同的构造函数并且类命名是一致的:

class car_factory
{
    function create_car($type = null)
    {
        if (is_null($type)) {
            return new car();
        }

        $class = "{$type}_car";
        if (class_exists($class)) {
            $obj = new $class();

            if ($obj instanceof car) {
                return $obj;
            }
        }

        throw new InvalidArgumentException($type);
    }
}
Run Code Online (Sandbox Code Playgroud)

我个人没有任何偏好; 如果可扩展性是一个关键因素,那就去吧,否则坚持一个简单的switch.