Php 类可以扩展或重写自己吗?
假设我们有一节课。我们从类中创建一个对象,当我们这样做时,类会根据对象初始化值扩展自己 例如:Php 类可以扩展或重写自己吗?,php,Php,假设我们有一节课。我们从类中创建一个对象,当我们这样做时,类会根据对象初始化值扩展自己 例如: $objectType1 = new Types(1); $objectType1->Activate(); // It calls an activation function for type 1 $objectType2 = new Types(2); $objectType2->Activate(); // It calls an activation function for
$objectType1 = new Types(1);
$objectType1->Activate(); // It calls an activation function for type 1
$objectType2 = new Types(2);
$objectType2->Activate(); // It calls an activation function for type 2
我不想使用类扩展的标准过程:
class type1 extends types{}
不能在运行时扩展类。使用实例变量区分这两种类型,或使用实例变量 实例变量的示例:
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();
更新:
因为PHP5.3可以使用。也许您可以利用它。您不能在运行时扩展类。使用实例变量区分这两种类型,或使用实例变量 实例变量的示例:
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();
更新:
因为PHP5.3可以使用。也许你可以利用它。在Activate and==处用大写字母代替==就很好了。附言:换一个{}就好了too@Xavier:这只是一个粗略的示意图,应说明一般方法。以大写字母开头的方法名称很难看:)你是对的,但你应该告诉他,以大写字母开头的名称是为类保留的,以便使代码更易于阅读。在Activate and==处使用大写字母代替==将是完美的。附言:换一个{}就好了too@Xavier:这只是一个粗略的示意图,应说明一般方法。以大写字母开头的方法名称很难看:)你是对的,但你应该告诉他,以大写字母开头的名称是为类保留的,以便使代码更易于阅读。