tags:

views:

74

answers:

4

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?

+3  A: 

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.

jasonbar
Thank you, really cleared things up. :)
Serg
+1  A: 

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).

Pekka
A: 
<?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);
scopus
this is wrong, and would cause infinite recursion.
Mike Sherov
I don't think this will turn out like you think it will..
jasonbar
Simple problem, simple solution.
scopus
A: 

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.

Mike Sherov