开发者

can php return a boolean? => return $aantal == 0;

开发者 https://www.devze.com 2022-12-10 16:42 出处:网络
can php return a boolean like this: return $aantal == 0; like in java you can public boolean test(int i)

can php return a boolean like this:

return $aantal == 0;

like in java you can

public boolean test(int i)
{
return i==0;
}

or do you Have to use a if contruction? because if i do this.

$foutLoos = checkFoutloos($aantal);

function checkFoutloos($aantal)
{
    return $aantal == 0;
}

echo "foutLoos = $开发者_如何学运维foutLoos"; 

it echo's

foutLoos = 

so not true or false

thanks matthy


It returns a boolean, but the boolean is not converted to a string when you output it. Try this instead:

$foutLoos = checkFoutloos($aantal);

function checkFoutloos($aantal)
{
    return $aantal == 0;
}

echo "foutLoos = " . ( $foutLoos ? "true" : "false" );


Try it out!

function is_zero($n) {
    return $n == 0;
}

echo gettype(is_zero(0));

The output:

boolean


yes ideed i found out that when you echo a false you get nothing and true echo's 1 thats why i was confused ;)


Yes. you can even through in the ternary operator.

function foo($bar == 0) {
    return ($bar) ? true : false;
}


Yes, you can return a boolean test in the return function. I like to put mine in parenthesis so I know what is being evaluated.

function Foo($Bar= 0) {
    return ($Bar == 0);
}

$Return = Foo(2);
$Type = var_export($Return, true);

echo "Return Type: ".$Type; // Return Type: boolean(true)

In fact, almost anything can be evaluated on the return line. Don't go crazy though, as it may make refactoring more difficult (if you want to allow plugins to manipulate the return, for instance).


You could just do it like this i think, with type casting:

return (bool) $aantal; 
0

精彩评论

暂无评论...
验证码 换一张
取 消