noober
noober

Reputation: 4938

How to pass type into a function in PHP

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).

Upvotes: 2

Views: 357

Answers (2)

Niko
Niko

Reputation: 26730

There is absolutely no need to do the casting inside the function (especially since PHP is loosely typed).

Consider the following use-case:

$booleanValue = ClassName::get_cookie('foo', true, 'bool');

You end up with the same amount of code (but much more readable!) when you do the casting outside of get_cookie():

$booleanValue = (bool) ClassName::get_cookie('foo', true);

However, you can still implement a simple switch for 'false' and 'true' strings, respectively:

public static function get_cookie($parameter, $default, $isPseudoBool = false) {
    $value = isset($_COOKIE[$parameter]) ? $_COOKIE[$parameter] : $default;

    if ($isPseudoBool) {
        $value = ($value === true || strcasecmp($value, 'true') === 0);
    }

    return $value;
}

If you still prefer to move the type conversion into the function, settype() is what you need for this:

public static function get_cookie($parameter, $default, $type) {
    $value = isset($_COOKIE[$parameter]) ? $_COOKIE[$parameter] : $default;
    settype($value, $type);
    return $value;
}

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.

Upvotes: 1

adrian7
adrian7

Reputation: 1016

Try this

public static function get_cookie($parameter, $default)
{

    if( empty($parameter) ) return $default;       

    return isset($_COOKIE[$parameter]) ? $_COOKIE[$parameter] : $default;
}

Upvotes: 0

Related Questions