Page 1 of 1

My first PHP routine - almost works but not quite !!!

Posted: Thu Nov 12, 2009 12:17 pm
by Kaps
pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


Dear All,

I have been teaching myself PHP - with some success. However, the following piece of code does not do what I thought it would. I wanted it to return the factorial values of the integers up to 10. Instead it just returns 0. Can anybody tell me why ? thanks

Kaps

Code: Select all

 
 
 
 
<?php
 
// Title : My first PHP script
// Author : Kaps
 
function factorial($num){
 
STATIC $factorial_Value;
$factorial_value = $factorial_value * $num;
printf(" factorial %d has the value %d </br>",$num,$factorial_value);
}
 
 
$upper=10;
 
for($i=1;$i<=$upper;$i++)
{
 printf(" value of i %d </br> ",$i);
factorial($i);
}
 

pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.

Re: My first PHP routine - almost works but not quite !!!

Posted: Thu Nov 12, 2009 1:55 pm
by pickle
PHP is case sensitive. You're declaring $factorial_Value (notice the capital V) as static, but using $factorial_value everywhere else. Consequently, $factorial_value will have a value of 0 which, when multiplied by anything, will return 0.

Re: My first PHP routine - almost works but not quite !!!

Posted: Thu Nov 12, 2009 3:22 pm
by Kaps
Thanks - well spotted. Is there an easy way of spotting these errors - or does it come with practice ? In VBA there is the command Option Explicit to highlight undeclared variables. Is there something similar in PHP ? Thanks

Kaps

Re: My first PHP routine - almost works but not quite !!!

Posted: Thu Nov 12, 2009 3:30 pm
by pickle
You can increase your error reporting level. Undeclared variables generate a "notice", which is an error that PHP handles very gracefully. Consequently, some servers don't report them.

At the top of your script, call this:

Code: Select all

error_reporting(E_ALL);
and you'll see all levels of reported errors.

I usually avoid things like this by having naming conventions. Objects are always capitalized. Constants and globals are always all uppercase. If I have a variable name with underscores, I never uppercase any of the letters (unless it's a constant or global of course). Mainly though, I'd say it just comes with practice.