我正在研究一个将用户注册到数据库中的注册函数。
我想在该函数中检查是否有任何参数为空。我已经简化了问题,所以这不是零售外观。
<?php
create_user($_POST["username"], $_POST["epost"]);
function create_user($username, $epost){
// Pull all the arguments in create_user and check if they are empty
// Instead of doing this:
if(empty($username) || empty($epost)){
}
}
这样做的原因是我可以简单地向函数添加另一个参数,它会自动检查它是否为空。
简短的问题:
如何检查函数中的所有参数是否为空?
答案 0 :(得分:3)
function create_user($username, $epost){
foreach(func_get_args() as $arg)
{
//.. check the arg
}
}
答案 1 :(得分:0)
您也可以使用array_filter
和array_map
功能
例如,创建一个如下所示的函数
<?php
function isEmpty( $items, $length ) {
$items = array_map( "trim", $items );
$items = array_filter( $items );
return ( count( $items ) !== (int)$length );
}
?>
上述函数接受两个参数。
$items = array of arguments,
$length = the number of arguments the function accepts.
你可以像下面那样使用它
<?php
create_user( $_POST["username"], $_POST["epost"] );
function create_user( $username, $epost ) {
if ( isEmpty( func_get_args(), 2 ) ) {
// some arguments are empty
}
}
?>