如何在类B方法中调用类A方法并使类A方法中的类B方法和参数可用?

时间:2010-08-24 23:24:22

标签: php oop

类用户     {

  private $_var_1 = 10;
  private $_var_2 = 20;

  private function _preExecute() {
    //do something here before executing sub-class's method
  }

  private function _postExecute() {
    //do something here after executing sub-class's method
  }

  private function _anyMethod() {
    echo "Hello!";
  }

  public function execute($action) {
    $this->_preExecute();
    $obj = new __CLASS__."_".$action;
    $obj->execute();
    $this->_postExecute();
  }

}

class User_Add 
{

  public function execute() {
    echo $this->_var1;
    echo $this->_var2;
    parent::_anyMethod();
  }

}

$user = new User();
$user->execute("Add");

因此,正如您所看到的,我希望能够从类User_Add访问User类的变量和方法,是否可以在PHP 5.2或更高版本中使用?

1 个答案:

答案 0 :(得分:0)

当然!

class User_Add extends User

但是User_Add类必须保护User类中的函数和变量,或者公共可访问它们。请查看php文档中的inheritance