php函数参数var,reset参数

php函数参数var,reset参数

问题描述:

I created a php function and I want to clear/reset the arguments of the function.

for example I've got this function declared twice in my index.php:

grid_init($type='portfolio',$postNb=4,$rowNb=2);
grid_init($type='post',$postNb,$rowNb);

function grid_init($type,$postNb,$rowNb) {
?>

<div class="container" data-type="<?php echo $type; ?>" data-postNb="<?php echo $rowNb; ?>" data-rowNb="<?php echo $rowNb; ?>">
some stuff.....
</div>

<?php
}

If I didn't specified my argument in my second function (in the above example $postNb $rowNb), these vars will take the values of the previous argument declared in the previous function ($postNb=4,$rowNb=2)...

How can I reset/clear my argument in my function between each function declared in a same file?

我创建了一个php函数,我想清除/重置函数的参数。 p>

例如我在index.php中声明了两次这个函数: p>

  grid_init($ type ='portfolio',$ postNb = 4,$  rowNb = 2); 
grid_init($ type ='post',$ postNb,$ rowNb); 
 
function grid_init($ type,$ postNb,$ rowNb){
?&gt; 
 
&lt; div class  =“container”data-type =“&lt;?php echo $ type;?&gt;”  data-postNb =“&lt;?php echo $ rowNb;?&gt;”  data-rowNb =“&lt;?php echo $ rowNb;?&gt;”&gt; 
some stuff ..... 
&lt; / div&gt; 
 
&lt;?php 
} 
  code>  
 
 

如果我没有在我的第二个函数中指定我的参数(在上面的示例 $ postNb $ rowNb code>中),这些变量将采用前一个参数的值 在上一个函数中声明( $ postNb = 4,$ rowNb = 2 code>)... p>

如何在每个函数之间重置/清除我的函数 函数在同一个文件中声明? p> div>

To make a function have default arguments it's like:

function grid_init($type, $postNb = 2, $rowNb = 4){
  echo "<div class='container' data-type='$type' data-postNb='$rowNb' data-rowNb='$rowNb'>".
  "some stuff.....".
  '</div>';
}

Execute like:

grid_init('whatever'); // will assume $postNb = 2 and $rowNb = 4;
grid_init('some_data_type', 42, 11); // overwrite your defaults

You seem to have trouble calling functions.

Change your calls to

grid_init('portfolio',4,2);
grid_init('post','',''); // or use '' as default

a) you might have declared a function like this

function grid_init($type, $postNb, $rowNb)
{
   // do stuff on $tyoe, $postNb, $rowNb
}

b) you might call the function several times, each time with new parameters

grid_init('post', 5, 4);
grid_init('somewhere', 1, 2);

A function does not memorize values of prior calls. If you want that, then save them somewhere from within that function.

c) you might use default parameters on your function

Default parameters always come last in the function declaration.

function grid_init($type, $postNb = 2, $rowNb = 2)
{
    // do stuff on $tyoe, $postNb, $rowNb
}

call it

grid_init('somewhere');

now postNb, rowNb are not set, but the default values from the declaration are used.

d) keep the number of parameters low!