您不能在運行時擴展類。使用實例變量來區分這兩種類型或使用factory。
舉例實例變量:
class Types() {
private $type;
public function __construct($type) {
$this->type = $type;
}
public function activate() {
if($this->$type == 1) {
// do this
}
else if($this->type == 2) {
// do that
}
}
}
舉例工廠模式:
abstract class BaseClass {
// Force Extending class to define this method
abstract public function activate();
// Common method
public function printOut() {
echo "Hello World";
}
}
class Type1 extends BaseClass {
public function activate() {
// do something
}
}
class Type2 extends BaseClass {
public function activate() {
// do something else
}
}
class TypeFactory {
public static function getType($tpye) {
if($type == 1) {
return new Type1();
}
else if($type == 2) {
return new Type2();
}
}
}
那麼你做的事:
$obj = TypeFactory::getType($1);
$obj->activate();
更新:
自PHP 5.3以來,您可以使用anonymous functions。也許你可以利用這個。
Whith在Activate和===的大寫字母而不是==,它將是完美的。 PS:其他{}也會很好 – xavierm02 2010-04-10 12:02:06
它不是重寫,但是ty – EBAG 2010-04-10 12:05:27
@Xavier:這只是一個粗略的草圖,應該演示一般的方法。以大寫字母開頭的方法名稱很難看:) – 2010-04-10 12:07:18