PHP 函数返回布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4933100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:18:04  来源:igfitidea点击:

PHP function returning boolean

phpboolean

提问by Cyril Horad

How can I have a booleanreturning function?
I mean like this on other programming language.

我怎样才能有boolean返回功能?
我的意思是在其他编程语言上是这样的。

return true; // return false

回答by blanknamefornow

The question does not entirely make sense, because you have not asked something you've already solved.

这个问题并不完全有意义,因为你还没有问你已经解决的问题。

The function in PHP can be done like this.

PHP中的函数可以这样完成。

function check($int) {
   if ($int == 3) {
      return true;
   } else {
      return false;
   }
}
if (check(3)) echo "Returned true!";

回答by Mark Baker

Incredibly enough

令人难以置信

return true;

e.g.

例如

function testIfABC($x) {
    if ($x === 'ABC') {
        return true;
    }
    return false;
}

though that could more easily be written as:

虽然这可以更容易地写成:

function testIfABC($x) {
    return ($x === 'ABC');
}

which will still return a boolean value

它仍然会返回一个布尔值

回答by oopbase

<?php

  function doSomething() {
    return true;
  }

The function you need could look like this:

您需要的功能可能如下所示:

  function check($var, $length) { 
    return (strlen($var)<=$length) && (isset($var));
  }

?>

回答by mario

As a more practical example, you can use any boolean expression as result:

作为一个更实际的例子,你可以使用任何布尔表达式作为结果:

return ($data != "expected") or ($param == 17);

回答by Gleb Kemarsky

Since PHP 5.5 you can use the boolvalfunction:

自 PHP 5.5 起,您可以使用该boolval函数:

(PHP 5 >= 5.5.0, PHP 7) boolval — Get the boolean value of a variable

(PHP 5 >= 5.5.0, PHP 7) boolval — 获取变量的布尔值

return boolval( $result );

Or just convert to boolean. But perhaps all this is not necessary:

或者只是转换为 boolean。但也许这一切都没有必要:

To explicitly convert a value to boolean, use the (bool)or (boolean)casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.

要将值显式转换为布尔值,请使用(bool)或 (boolean)强制转换。但是,在大多数情况下,强制转换是不必要的,因为如果运算符、函数或控制结构需要布尔参数,则会自动转换值。

return (bool) $result;
return (boolean) $result;

回答by EvilCoder

I do understand the question, as in visual C# you can define a function to return bool only. This is not the case in PHP. You can just use function blabla($val) { return ($val == "yes" ? true : false); }. No support for "public bool($value) { return true; // false }"

我确实理解这个问题,因为在 Visual C# 中,您可以定义一个仅返回 bool 的函数。在 PHP 中不是这种情况。你可以只使用 function blabla($val) { return ($val == "yes" ? true : false); }. 不支持“public bool($value) { return true; // false }”