English 中文(简体)
• 如何通过购买力平价功能中的具体变量
原标题:How to pass specific variable in PHP function

我有一套PHP功能,需要3个参数。 我想把它当作第1和第3个参数的价值,但我希望第2个参数会落空。

我怎么能具体说明我通过什么,否则,它就被解释为我通过第1和第2个位置的数值。

感谢。

最佳回答

不能“通过”参数,该参数在参数清单末尾:

  • if you want to specify the 3rd parameter, you have to pass the 1st and 2nd ones
  • if you want to specify the 2nd parameter, you have to pass the 1st one -- but the 3rd can be left out, if optionnal.

在你的情况下,你必须给2个参数——最好是缺省——带来价值;如果是,这要求你知道这一缺省价值。


A possible alternative would be not have your function take 3 parameters, but only one, an array :

function my_function(array $params = array()) {
    // if set, use $params[ first ]
    // if set, use $params[ third ]
    // ...
}

并称之为这一职能:

my_function(array(
     first  =>  plop ,
     third  =>  glop 
));

这将使你能够:

  • accept any number of parameters
  • all of which could be optionnal

但:

  • your code would be less easy to understand, and the documentation would be less useful : no named parameters
  • your IDE would not be able to give you hints on which parameters the function accepts
问题回答

一旦确定一个缺省参数,就不需要该参数之后的所有参数。 你可以做这样的事情:

const MY_FUNCTION_DEFAULT = "default";

public function myFunction($one, $two = "default", $three = 3)
{
   if (is_null($two)) $two = self::MY_FUNCTION_DEFAULT;
   //...
}

// call
$this->myFunction(1, null, 3);

http://www.php.net/manual/en/Function.func-get-args.php





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签