将 PHP 函数返回值转换为 true/false

4

我最初参考了这个,但它没有解决我的问题。

我有一个类似这样的东西:

  $message .=   "\n\tWhether $testOutputDir is a directory:" . (!!is_dir($testOutputDir))
                . "\n\tWhether $outputDir is a directory:" . is_dir($outputDir)
                . "\n\tWhether $outputDir is readabale:" . is_readable($outputDir)
                ....

我想要打印以下内容: ```html

我只是想打印一些东西:

```
       Whether /a is a directory: true
       Whether /b is a directory: true

但它的打印结果如下:
       Whether /a is a directory: 1
       Whether /b is a directory: 1

有什么建议可以解决这个问题吗?
编辑:
我可以检查func == 1 ? TRUE : FALSE。但我希望有一个简单的转换或类似的方法。

即使您执行 echo true,它仍然会打印 1。因此需要一个 bool2str 函数。 - Fabricator
@Fabricator 那我应该使用三元运算符。这是唯一的方法吗? - Gibbs
3个回答

1
在PHP中,当布尔值转换为字符串时,true会转换成'1'false会转换成空字符串''。如果您想要其他结果,您需要显式地将布尔值转换为字符串。
没有任何强制转换可以得到您想要的结果。解决问题的一种方法是将您的值传递到此函数中:
function stringForBool($bool) {
    return ($bool ? 'true' : 'false');
}

//use like:
echo stringForBool(isReadable($outputDir));

你也可以将此函数直接内联到代码中,而不是调用它,但如果你使用它超过几次,那将变得非常重复。

其他答案建议使用json_encode()。虽然这肯定有效(如果传递布尔值),但如果传递的不是完全等于truefalse的内容,则不会得到预期的输出。当然,你可以调用json_encode((bool)$yourValue),这将给你想要的结果,但(在我看来)它有些神奇而不太明确。


0

你将陷入做这件事的困境:

is_dir($outputDir) ? 'true' : 'false'

在PHP中将bool转换为string时,始终会将其转换为"""1"
现在,这有点像黑客技巧,但实际上你可以使用json_encode()
php > var_dump(json_encode(true));
string(4) "true"

不完全正确。(string)false 会导致空字符串。 - jbafford

0

这可能有效,

echo json_encode(true);  // string "true"

echo json_encode(false); // string "false"

所以,

 $message .=   "\n\tWhether $testOutputDir is a directory:" . json_encode(!!is_dir($testOutputDir))
                . "\n\tWhether $outputDir is a directory:" . json_encode(is_dir($outputDir))
                . "\n\tWhether $outputDir is readabale:" . json_encode(is_readable($outputDir))

嗨,谢谢。您的回答与三元运算符的使用有何不同? - Gibbs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接