我无法理解这段非常简单的 PHP 代码。请帮忙?
代码如下:
<?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 语句?
Here's the code:
<?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);
}
}
In the method insert(), what does parent::insert($data)
do? Is it calling itself? Why would it do that? Why is that return statement run, regardless of the IF conditional?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它调用 Zend_Db_Table_Abstract 类上的 insert 方法。仅当条件失败时才会执行 return 语句。
throw new Exception 将抛出异常并将执行返回到调用该方法的位置。
It's calling the insert method on the Zend_Db_Table_Abstract class. The return statement will only be executed if the conditional fails.
throw new Exception will throw an exception and return execution to the place that invoked the method.
parent::insert($data)
调用 insert() 函数的父实现,即Zend_Db_Table_Abstract
这样,就有可能向新类添加自定义检查,并仍然使用父类实现中的代码(而不必将其复制+粘贴到函数中)。
parent::insert($data)
calls the parent implementation of the insert() function, i.e. that ofZend_Db_Table_Abstract
That way, it is possible to add a custom check to the new class, and still make use of the code in the parent class implementation (instead of having to copy+paste it into the function).
parent::
与关键字self::
或YourClassNameHere::
类似,用于调用静态函数,但>parent
将调用当前类扩展的类中定义的函数。另外, throw 语句是函数的退出点,因此如果执行 throw,函数将永远不会到达 return 语句。如果引发异常,则由调用函数使用
try
和catch
捕获并处理异常,或者允许异常在调用堆栈中进一步传播。parent::
is similar to the keywordself::
orYourClassNameHere::
in that it is used to called a static function, exceptparent
will call the function that is defined in the class that the current class extends.Also, a
throw
statement is an exit point from a function, so if the throw is executed, the function would never get to thereturn
statement. If an exception is thrown, it is up to the calling function to either catch and process the exception usingtry
andcatch
or allow the exception to propagate further up the call stack.调用这个类
Call this class