LMPX.COM |
Home | Linux | Mysql | PHP | XML | ||
|
|
|||
From: wbcarts@juno.com Date: Mon Oct 6 12:59:43 2008 Subject: note 86171 added to language.types.boolean
CODING PRACTICE...
Much of the confusion about booleans (but not limited to booleans) is the fact that PHP itself automatically makes a type cast or conversion for you, which may NOT be what you want or expect. In most cases, it's better to provide functions that give your program the exact behavior you want.
<?php
function boolNumber($bValue = false) { // returns integer
return ($bValue ? 1 : 0);
}
function boolString($bValue = false) { // returns string
return ($bValue ? 'true' : 'false');
}
$a = true; // boolean value
echo 'boolean $a AS string = ' . boolString($a) . '<br>'; // boolean as a string
echo 'boolean $a AS number = ' . boolNumber($a) . '<br>'; // boolean as a number
echo '<br>';
$b = (45 > 90); // boolean value
echo 'boolean $b AS string = ' . boolString($b) . '<br>'; // boolean as a string
echo 'boolean $b AS number = ' . boolNumber($b) . '<br>'; // boolean as a number
echo '<br>';
$c = boolNumber(10 > 8) + boolNumber(!(5 > 10)); // adding booleans
echo 'integer $c = ' . $c .'<br>';
?>
Results in the following being printed...
boolean $a AS string = true
boolean $a AS number = 1
boolean $b AS string = false
boolean $b AS number = 0
integer $c = 2
In other words, if we know what we want out of our program, we can create functions to accommodate. Here, we just wanted 'manual control' over numbers and strings, so that PHP doesn't confuse us.
----
Server IP: 69.147.83.197
Probable Submitter: 67.150.174.235
----
Manual Page -- http://www.php.net/manual/en/language.types.boolean.php
Edit -- https://master.php.net/note/edit/86171
Del: integrated -- https://master.php.net/note/delete/86171/integrated
Del: useless -- https://master.php.net/note/delete/86171/useless
Del: bad code -- https://master.php.net/note/delete/86171/bad+code
Del: spam -- https://master.php.net/note/delete/86171/spam
Del: non-english -- https://master.php.net/note/delete/86171/non-english
Del: in docs -- https://master.php.net/note/delete/86171/in+docs
Del: other reasons-- https://master.php.net/note/delete/86171
Reject -- https://master.php.net/note/reject/86171
Search -- https://master.php.net/manage/user-notes.php
| Navigate in group php.notes at sever news.php.net | |
| Previous | Next |
| © No Copyright You are free to use Anything |
Site Maintained by PHP Developer
Powered By PHP Consultants |