Re: Fatal error when calling nested function

From: Date: Fri, 26 Oct 2007 09:02:27 +0000
Subject: Re: Fatal error when calling nested function
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-263693@lists.php.net to get a copy of this message
Edward Kay wrote:
Here's the list : <?php function salestax($price,$tax) { function convert_pound($dollars, $conversion=1.6) { return $dollars * $conversion; } $total = $price + ($price * $tax); echo "Total cost in dollars: $total. Cost in British pounds: " .convert_pound($total); } echo convert_pound(15); ?> I get the following error : *Fatal error*: Call to undefined function convert_pound() in ...*Untitled-1.php* on line *18 *line 18 is this one : echo convert_pound(15);
    
From http://www.daaq.net/old/php/index.php?page=php+adv+functions&parent=php+flow +control: "When you define a function within another function it does not exist until the parent function is executed. Once the parent function has been executed, the nested function is defined and as with any function, accessible from anywhere within the current document. If you have nested functions in your code, you can only execute the outer function once. Repeated calls will try to redeclare the inner functions, which will generate an error." So, as you're not calling salestax() anywhere, the convert_pound function isn't defined. I wasn't aware of nested functions before your question, but reading the above on how the declaring function can only be called once, I feel they are best avoided. Does anyone have anyone have any examples where using them would be beneficial? E Ok.If I use the code below :
<?php function salestax($price,$tax) { function convert_pound($dollars, $conversion=1.6) { return $dollars * $conversion; } $total = $price + ($price * $tax); echo "Total cost in dollars: $total. Cost in British pounds: " .convert_pound($total); } salestax(15.00,.075); echo convert_pound(15); ?> I get no errors but I still get only the 1st line executed.

« previous php.general (#263693) next »