note 86180 added to language.types.integer

From: Date: Tue, 07 Oct 2008 01:25:22 +0000
Subject: note 86180 added to language.types.integer
Groups: php.notes 
Request: Send a blank email to php-notes+get-145112@lists.php.net to get a copy of this message
PHP offers a slew of built-in functions and automatic type-casting routines which can get pretty complicated. But most of the time, you still have to take matters into your own hands and allow PHP to do its thing. In that case, and something that has NOT been mentioned, is how to construct your code. To keep things simple, I divide all my scripts in half. The top half gives my scripts the "capability" they need, and the lower half is the actual code to be "run" or "executed". <?php /* * build the program's capability - define variables and functions... */ $item_label = ''; // type string $item_price = 0.0; // type float $item_qty = 1; // type integer $item_total = 0.0; // type float - to set use calculate() function calculate(){ global $item_price, $item_qty, $item_total; $item_price = number_format($item_price, 2); $item_total = number_format(($item_price * $item_qty), 2); } function itemToString() { global $item_label, $item_price, $item_qty, $item_total; return "$item_label [price=\$$item_price, qty=$item_qty, total=\$$item_total]"; } /* * run the program - set data, call methods... */ $item_label = "Coffee"; $item_price = 3.89; $item_qty = 2; calculate(); // set $item_total echo itemToString(); // -> Coffee [price=$3.89, qty=2, total=$7.78] $item_label = "Chicken"; $item_price = .80; // per lb. $item_qty = 3.5; // lbs. calculate(); // set $item_total echo itemToString(); // -> Chicken [price=$0.80, qty=3.5, total=$2.80] ?> Note: All type-casting is done by PHP's built-in number_format() method. This allows our program to enter any number (float or int) on item price or quantity in the runtime part of our script. Also, if we explicitly cast values to integer in the capability part of our script, then we start getting results that may not be desirable for this program. For example, if in the calculate method we cast item_qty to integer, then we can no longer sell chicken by the pound! ---- Server IP: 69.147.83.197 Probable Submitter: 67.150.120.40 ---- Manual Page -- http://www.php.net/manual/en/language.types.integer.php Edit -- https://master.php.net/note/edit/86180 Del: integrated -- https://master.php.net/note/delete/86180/integrated Del: useless -- https://master.php.net/note/delete/86180/useless Del: bad code -- https://master.php.net/note/delete/86180/bad+code Del: spam -- https://master.php.net/note/delete/86180/spam Del: non-english -- https://master.php.net/note/delete/86180/non-english Del: in docs -- https://master.php.net/note/delete/86180/in+docs Del: other reasons-- https://master.php.net/note/delete/86180 Reject -- https://master.php.net/note/reject/86180 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#145112) next »