Jump to content

why declare the variable


jimfog

Recommended Posts

function calculate_items($cart){$items=0if(is_array($cart)){foreach ($cart as $isbn=>$qty){$items +=$qty;}}return $items;}

Take a look at the above code-it is from a shopping cart application. The question is the following:Why the $items variable is declared with a value of zero? Can we just omit that?

Link to comment
Share on other sites

$items doesn't have a value if you don't set it. $items += $qty wouldn't mean anything if $items wasn't set to a value. You can't add a number to something that's not a number.

Link to comment
Share on other sites

if $items is not defined it will be null after that if you use any arithmatic oprator it will be converted to ineteger. But this type casting NULL to integer result is undefined and should not be relied (if you run the code removing the declaration it will run well but with some notices) In other strict languages you must define ant variable before you use in case of php it does not matter much cause it will still run with some notices. but it is considered as secuirty faults so it must be avoided and must declare variables before you use.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...