【发布时间】:2013-05-16 14:33:02
【问题描述】:
有什么方法可以让它工作吗?见例子:
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";
}
}
所以目标是这样使用它:
$mycar = new car('big');
$mycar->whatisit(); // i want it to say that it's big
我很想这是不好的方式,它不能以这种方式工作,但也许有一个技巧?
PS:: 我知道我可以为此使用特殊的静态方法,但是...
【问题讨论】:
-
构造函数不能在 PHP 中返回值;你需要另一种方法。
-
@kitty 为你的昵称+头像点赞。
-
你需要添加一个“汽车”界面和一个“汽车”工厂 - 试图同时做这两个是丑陋和困难的。
标签: php class oop constructor