note 75291 deleted from function.is-bool by tularis
| From: | tularis@php.net | Date: | Fri, 25 May 2007 22:57:23 +0000 |
| Subject: | note 75291 deleted from function.is-bool by tularis | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-126915@lists.php.net to get a copy of this message | ||
Note Submitter: emanueledelgrande at email dot it
----
I think there's a hole in the PHP typecasting methods:
you have the (int) function, the (float) function and the (string) function, but no function to
force a string variable into the boolean type.
It's obvious that forcing unconditionally the type of variables into arrays and objects is
inappropriate, but boolean type is the most basic one for each programming language, that's why
I guessed that a (bool) function already existed.
Moreover, with the increasing trend of RSS data streaming, the parsing of an XML string into an
object often requires to typecast as boolean values the content of XML tags, normally returned as
string by the object method get_content().
I wrote the following function, which also uses a "native PHP style" error message:
<?php
// strings tyecasting as boolean values:
function bool($var) {
switch (strtolower($var)) {
case ("true"):
return true;
break;
case ("false"):
return false;
break;
default:
die("<br />\n<b>Warning:</b> Invalid argument supplied for
".__FUNCTION__." function in <b>".__FILE__."</b> on line
<b>".__LINE__."</b>: the argument can contain only 'true' or
'false' values as a string.<br />\n");
}
}
?>
Here it is a small example:
<?php
$xmlResponse = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
$xmlResponse .= "<Result>";
$xmlResponse .= "<AuthError>false</AuthError>";
$xmlResponse .= "<TransferStatus>true</TransferStatus>";
$xmlResponse .= "</Result>";
if (! $responseDoc = domxml_open_mem($xmlResponse, DOMXML_LOAD_PARSING, $XmlParsingError)) {
echo "Error while parsing the XML string:<br />".print_r($XmlParsingError, TRUE);
} else {
$ResultNode = $responseDoc->get_elements_by_tagname('Result');
$AuthError = $ResultNode[0]->get_elements_by_tagname('AuthError');
$auth_error = bool($AuthError[0]->get_content());
$TransferStatus = $ResultNode[0]->get_elements_by_tagname('TransferStatus');
$transfer_status = bool($TransferStatus[0]->get_content());
if (! $auth_error) { echo "Auth OK<br />"; } else { echo "Auth error<br
/>"; }
if ($transfer_status) { echo "Transfer OK<br />"; } else { echo "Transfer
error<br />"; }
}
?>
It would be useful this function to be implemented in the core of PHP5.