0

这是代码:

<?php

 class Order extends Zend_Db_Table_Abstract
 {
 protected $_name = 'orders';

 protected $_limit = 200;

 protected $_authorised = false;

 public function setLimit($limit)
 {
 $this->_limit = $limit;
 }

 public function setAuthorised($auth)
 {
 $this->_authorised = (bool) $auth;
 }

 public function insert(array $data)
 {
 if ($data['amount'] > $this->_limit
 && $this->_authorised === false) {
 throw new Exception('Unauthorised transaction of greater than '
 . $this->_limit . ' units');
 }
 return parent::insert($data);
 }
 }

在方法 insert() 中,做了parent::insert($data)什么?它是在呼唤自己吗?为什么会这样做?为什么无论 IF 条件如何,都会运行该 return 语句?

4

4 回答 4

2

它调用 Zend_Db_Table_Abstract 类的 insert 方法。仅当条件失败时才会执行 return 语句。

throw new Exception 将抛出异常并将执行返回到调用该方法的地方。

于 2010-02-26T00:05:20.757 回答
0

parent::insert($data)调用insert() 函数的父实现,即Zend_Db_Table_Abstract

这样,可以向新类添加自定义检查,并且仍然使用父类实现中的代码(而不必将其复制+粘贴到函数中)。

于 2010-02-26T00:07:07.667 回答
0

parent::类似于关键字self::YourClassNameHere::用于调用静态函数,除了parent将调用在当前类扩展的类中定义的函数。

此外,throw语句是函数的退出点,因此如果执行 throw,函数将永远不会到达return语句。如果抛出异常,则由调用函数来捕获和处理异常trycatch或者允许异常进一步向上传播到调用堆栈。

于 2010-02-26T00:09:53.883 回答
-1
<?php

 class Order extends Zend_Db_Table_Abstract
 {
 protected $_name = 'orders';

 protected $_limit = 200;

 protected $_authorised = false;

 public function setLimit($limit)
 {
 $this->_limit = $limit;
 }

 public function setAuthorised($auth)
 {
 $this->_authorised = (bool) $auth;
 }

 public function insert(array $data)
 {
 if ($data['amount'] > $this->_limit
 && $this->_authorised === false) {
 throw new Exception('Unauthorised transaction of greater than '
 . $this->_limit . ' units');
 }
 return $this->insert($data);
 }
 }

调用这个类

$order = new Order();
$order->insert($data);
于 2010-02-26T00:09:47.673 回答