PHP中的对象切片

Is it possible to get the base object from derived object in php

Something like this

class base {}
class derived extends base{
public function getBase()
{
         return (base)$this;
}

The above code, throws out a error

You can use parent:: to resolve to a parent method, property or constant.

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() {
  }
}