编程,使用全局变量的逻辑
programming, logic using gloabal variables
假设我有一个函数 add()。
function add(){
if (a)
return true;
if (b)
return true;
if (c)
insert into table.
return true;
}
现在我调用这个函数 add() 并且我只想在像条件 C 这样的插入执行时增加我的计数器。我也不想更改 return 值,它是真的。现在我的问题是如何确定 C 部分是否已执行?
我以为我可以在条件 c 中使用全局变量,如下所示
if (c)
{
insert into table.
$added = true;
return true;
}
然后我检查
if(isset($added && $added==true))
$count++;
但我想知道是否有任何我可以添加的参数或我可以使用的其他方法?
在您的插入周围添加一个 if,并添加一个计数器作为参数:
$count = 0;
function add(&$count){
if (a)
return true;
if (b)
return true;
if (c)
if(insert into table){ //Queries return a boolean
$count++;
}
return true;
}
add($count); //If insertion was succesful it added 1 to counter.
echo $count; //Returns either 1 or 0 depending on insert statement.
您可以通过引用传递参数。在 PHP 中,这是通过在前面加上井号 (&
) 来完成的。结果是您的函数没有获得该值的副本,而是一个引用原始值的变量,因此您可以在函数内部更改它。
function add(&$itemsAdded)
{
$itemsAdded = 0;
[...]
/* if added something */
$itemsAdded++;
}
在您的调用代码中
add($added);
$counter += $added;
假设我有一个函数 add()。
function add(){
if (a)
return true;
if (b)
return true;
if (c)
insert into table.
return true;
}
现在我调用这个函数 add() 并且我只想在像条件 C 这样的插入执行时增加我的计数器。我也不想更改 return 值,它是真的。现在我的问题是如何确定 C 部分是否已执行? 我以为我可以在条件 c 中使用全局变量,如下所示
if (c)
{
insert into table.
$added = true;
return true;
}
然后我检查
if(isset($added && $added==true))
$count++;
但我想知道是否有任何我可以添加的参数或我可以使用的其他方法?
在您的插入周围添加一个 if,并添加一个计数器作为参数:
$count = 0;
function add(&$count){
if (a)
return true;
if (b)
return true;
if (c)
if(insert into table){ //Queries return a boolean
$count++;
}
return true;
}
add($count); //If insertion was succesful it added 1 to counter.
echo $count; //Returns either 1 or 0 depending on insert statement.
您可以通过引用传递参数。在 PHP 中,这是通过在前面加上井号 (&
) 来完成的。结果是您的函数没有获得该值的副本,而是一个引用原始值的变量,因此您可以在函数内部更改它。
function add(&$itemsAdded)
{
$itemsAdded = 0;
[...]
/* if added something */
$itemsAdded++;
}
在您的调用代码中
add($added);
$counter += $added;