是否可以从 php 中的派生对象中获取基础对象
像这样的东西
class base {}
class derived extends base{
public function getBase()
{
return (base)$this;
}
上面的代码,抛出一个错误
是否可以从 php 中的派生对象中获取基础对象
像这样的东西
class base {}
class derived extends base{
public function getBase()
{
return (base)$this;
}
上面的代码,抛出一个错误
您可以使用它parent::
来解析为父方法、属性或常量。
If you're trying to get the name of the base class, here's a way to do that:
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();
Edit: When you use inheritance to extend a class (eg: derived extends base
), you are saying that derived
is a kind of base
, and all instances of derived
are also instances of base
. In most OO languages, the two instances, base
and derived
are not separate entities, and they can not be treated separately. (C++ is an exception to the rule in this regard).
If you need to treat the instances separately, then inheritance is the wrong tool for the job. Use extension by containment, rather than inheritance. This will look something like the following:
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() {
}
}