PHP函数乍一看可以返回不同的和多值,但它不能


PHP function can return different & multi-values at first sight, but it can not

<?php
function some_func(){
 return 'some_str_type' && 'another_str_type';
}
function another_func(){
 return '123' || '456';
}

print some_func(); //1 - the same as true
print another_func(); //again prints 1, as true

任何语言的简洁编码风格都要求将非小函数放入小函数 - 因为一个函数应该返回单个值。

但是,我在一些流行的 php 模板 langs (smarty, dwoo) 的源代码中看到了这种方法。那是什么呢?什么时候以这种方式编码?(指任何现实世界的情况)

PHP 将返回 1 个值。您在上面所做的是键入一个表达式,该表达式经过计算,并返回生成的布尔值。

return 'some_str_type' && 'another_str_type';

成为

return true && true;

成为

return true;

在现实生活中何时使用:

function some_func(){
   $success1 = doStuff1();
   $success2 = dostuff2();
   return $success1 && $success2;
}

如果两个调用的函数都返回 true,它将返回 true。