如果未设置某些变量,如何在不抛出任何错误的情况下调用函数?
例如,我需要logUserActivity($uName,$uId)
。如果用户登录并且这两个变量都已设置,这将正常工作。但是,如果用户未登录,则无法正常工作,并且会抛出错误。
在那种情况下,可以做些什么来使这两个值为NULL?
我这样做了:logUserActivity($uName=NULL,$uId=NULL)
但这使它们永远为NULL。
我也做了function logUserActivity($uName=NULL, $uId=NULL)
,这仍然会引发错误。
答案 0 :(得分:0)
您必须设置函数的默认值才能使其成为可选项
喜欢试试这个
function logUserActivity($uName='', $uId='')
答案 1 :(得分:0)
function logUserActivity($uName=NULL, $uId=NULL){
if($uName != ''){
echo 'Uname is set - '.$uName;
}
if($uId != ''){
echo 'uId is set - '.$uId;
}
}
logUserActivity(NULL,20);//O/p - uId is set - 20
logUserActivity('Test',NULL);//O/p - Uname is set - Test
logUserActivity('Test',20);//O/p - uId is set - 20,uId is set - 20
logUserActivity(NULL,NULL);//NO O/p
答案 2 :(得分:0)
像这样写:
function logUserActivity($uName=NULL, $uId=NULL) // If nothing is passed it will take it as null
{
if($uName==NULL && $uId == NULL) {
//User is not logged in
}
else
{
//user is logged in
}
}
并在用户登录时将其称为
logUserActivity("userName", 12345);
当用户未登录时
logUserActivity();
有关详细信息,请查看以下内容:http://us2.php.net/manual/en/functions.arguments.php
答案 3 :(得分:0)
function logUserActivity($uName=null,$uId=null) {
if ( !isset($uName) || !$uName ) {
$uName = 'some default'; // optionally, return; could be sued
}
if ( !isset($uId) || !$uId) {
$uId = 'some default'; // optionally, return; could be sued
}
}