【问题标题】:I'm having trouble understanding this really simple PHP code. Please help?我无法理解这个非常简单的 PHP 代码。请帮忙?
【发布时间】:2010-02-26 00:02:55
【问题描述】:
代码如下:
<?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 语句?
【问题讨论】:
标签:
php
model-view-controller
zend-framework
model
zend-db
【解决方案1】:
它调用 Zend_Db_Table_Abstract 类的 insert 方法。仅当条件失败时才会执行 return 语句。
throw new Exception 会抛出异常并返回执行到调用方法的地方。
【解决方案2】:
parent::insert($data)调用insert()函数的父实现,即Zend_Db_Table_Abstract的父实现
这样,可以向新类添加自定义检查,并且仍然使用父类实现中的代码(而不必将其复制并粘贴到函数中)。
【解决方案3】:
parent:: 与关键字self:: 或YourClassNameHere:: 类似,用于调用静态函数,但parent 将调用当前类扩展的类中定义的函数。
另外,throw 语句是函数的退出点,因此如果执行 throw,函数将永远不会到达 return 语句。如果抛出异常,则由调用函数使用try 和catch 捕获并处理异常,或者允许异常在调用堆栈中向上传播。
【解决方案4】:
<?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);