I have the following function to safely get a cookie:
public static function get_cookie($parameter, $default)
{
return isset($_COOKIE[$parameter]) ? $_COOKIE[$parameter] : $default;
}
When I try to read false then use it in ternary operator, I see the value is treated as string (which is casted to true).
I want to pass a type into this function and cast the value, but have no ideas how.
UPDATE
As Niko pointed, casting ‘false’ to boolean doesn’t work: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
I guess, I have to store strings in cookies always. (For instance, ‘yes’ and ‘no’ instead of ‘false’ and ‘true’ for my case).
There is absolutely no need to do the casting inside the function (especially since PHP is loosely typed).
Consider the following use-case:
You end up with the same amount of code (but much more readable!) when you do the casting outside of
get_cookie():However, you can still implement a simple switch for ‘false’ and ‘true’ strings, respectively:
If you still prefer to move the type conversion into the function,
settype()is what you need for this:But please note that this won’t convert a string “false” to the boolean value
false, if you specify$type = 'bool'– the conversion rules are the same as when an implicit conversion is done by the interpreter.