是否可以从php
中的派生对象获取基础对象像这样的东西
class base {}
class derived extends base{
public function getBase()
{
return (base)$this;
}
上面的代码,抛出错误
答案 0 :(得分:0)
您可以使用parent::
来解析父方法,属性或常量。
答案 1 :(得分:0)
如果您正在尝试获取基类的名称,请执行以下操作:
class base {
public function getClassName() {
return "base";
}
}
class derived extends base{
public function getBaseClassName() {
return parent::getClassName();
}
public function getClassName() {
return "derived";
}
}
$d = new derived();
echo $d->getBaseClassName();
编辑:当您使用继承扩展某个类(例如:derived extends base
)时,您说derived
是一种 base
,derived
的所有实例也是base
的实例。在大多数OO语言中,base
和derived
这两个实例不是单独的实体,不能单独处理。 (在这方面,C ++是规则的例外)。
如果您需要单独处理实例,那么继承是该作业的错误工具。通过包含使用扩展,而不是继承。这看起来如下所示:
class base {
public someBaseFunction() {
// ...
}
}
class derived {
/**
* each instance of `derived` *contains* an in instance of `base`
* that instance will be stored in this protected property
*/
protected $base;
/**
* constructor
*/
function __construct() {
// remember to call base's constructor
// passing along whatever parameters (if any) are needed
$this->base = new base();
// ... now do your constructor logic, if any ...
}
/**
* Here's the method that fetches the contained
* instance of `base`
*/
public function getBase() {
return $this->base;
}
/**
* If needed, `derived` can implement public elements
* from `base`'s interface. The logic can either delegate
* directly to the contained instance of base, or it can
* do something specific to `derived`, thus "overriding"
* `base`'s implementation.
*/
public function someBaseFunction() {
return $this->base->someBaseFunction();
}
/**
* of course, `derived` can implement its own public
* interface as well...
*/
public function someOtherFunction() {
}
}