这个问题也有类似的问题here和here。我本可以将此作为评论发布,但我还没有这个权限,所以我发布了此内容。我也发现类似的问题没有满足我的要求的答案。我将编写代码做进一步的讨论。
我是c/c++,你可以这样做:
void CallMe(int *p = NULL)
{
if ( p!= NULL )
*p = 0;
}
CallMe(); // Calling the function without arguments the function will do nothing. But...
int n;
CallMe(&n);
// Here, you are passing a pointer to your n that will be filled by the CallMe function.
For c/c++ programmer, you know what to expect on those two calls.
现在,我想用 PHP 来做。当我进行搜索时,搜索结果中建议的最流行方法如下:
isset
、is_null
和empty
。我进行了反复试验,但没有任何效果像 c/c++ 示例那样有效。
function CallMe(&$p=null)
{
if ($p==null)
return;
if(!isset($p))
return;
if (is_null($p))
return;
if (empty($p))
return;
$p = time();
return 'Argument was set to ' . $p;
}
CallMe();
在第一次不提供参数的调用中,所有参数计算结果都将为 true,并且该函数将不执行任何操作。让我们尝试争论一下。
$a = 1;
CallMe($a);
从源代码来看,该函数现在可以从 $a 变量中获得一些意义。但是...
$a = null;
CallMe($a);
在最后一次调用中,函数的行为就像没有给出参数一样。
现在,我想要实现的是能够检查(如 c/c++ 示例)是否提供了参数的函数。或者,有没有一种方法可以将指针传递给 PHP 中的变量?
您可以调用一个旧函数来检查用户实际提供的函数参数的数量:func_num_args()
function CallMe(&$p=null)
{
if (func_num_args() === 0)
{
// no argument supplied. do nothing.
return;
}
$p = time();
return 'Argument was set to ' . $p;
}
echo "Try supplying no argument:\n";
echo "---\n";
var_dump(CallMe());
echo "\n";
echo "Try supplying a variable with a value of null:\n";
echo "---\n";
$a = null;
var_dump($a);
var_dump(CallMe($a));
var_dump($a);
输出:
Try supplying no argument:
---
NULL
Try supplying a variable with a value of null:
---
NULL
string(30) "Argument was set to 1715217065"
int(1715217065)