简体   繁体   中英

Why would this line of code be executed if the IF condition is false? Doesn't make any sense

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);
 }
 }

Why would that method run ONLY if the condition fails. I'm a C# programmer, I my logic dictates that it will run regardless of the IF, correct? Thanks a million.

When you throw an exception, that usually causes the remaining code to exit unless you have a try...catch statement. Thus, if the amount is greater than 200 and the user is not authorized, it will execute the block inside of the if statement.

The link you provided mentions that it will "bubble up" to a controller where it will be caught. Since it's not caught in your code above (the model), execution inside of the model stops and is passed up the stack to the controller. It does not return to your model, thus the line following the if will not be called.

Check out the PHP manual on exceptions for more information.

异常将中断代码执行。

即使在C#中,即使抛出异常,也不会执行代码。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM