delete
delete

Reputation:

I'm having trouble understanding this really simple PHP code. Please help?

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?

Upvotes: 0

Views: 142

Answers (4)

Mike Sherov
Mike Sherov

Reputation: 13427

parent:: is similar to the keyword self:: or YourClassNameHere:: in that it is used to called a static function, except parent 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 the return statement. If an exception is thrown, it is up to the calling function to either catch and process the exception using try and catch or allow the exception to propagate further up the call stack.

Upvotes: 0

Can Aydoğan
Can Aydoğan

Reputation: 1040

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

Call this class

$order = new Order();
$order->insert($data);

Upvotes: -1

Pekka
Pekka

Reputation: 449395

parent::insert($data) calls the parent implementation of the insert() function, i.e. that of Zend_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).

Upvotes: 0

jasonbar
jasonbar

Reputation: 13461

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.

Upvotes: 2

Related Questions