php maker中文手册,函数的参数 - [ php中文手册 ] - 在线原生手册 - php中文网

用户评论:

[#1]

ohcc at 163 dot com [2015-11-08 09:23:50]

As of PHP 5.6, you can use an array as arguments when calling a function with the ... $args syntax.

$args= array('wu','WU','wuxiancheng.cn');$string=str_replace(...$args);

echo$string;?>

Ha ha, is that interesting and powerful?

Also you can use it like this

$args= array('WU','wuxiancheng.cn');$string=str_replace('wu', ...$args);

echo$string;?>

It also can be used to define a user function.

echo'

';print_r($otherArgs);print_r(func_get_args());

echo'

';

}wxc(1,2, ...array(3,4,5));?>

REMEMBER this: ... $args is not supported in PHP 5.5 and older versions.

[#2]

d_maley at hotmail dot com [2015-08-26 09:12:15]

If you define your functions in the following way, you can call them whilst only specifying the default parameters you need

1. Define your function with its mandatory parameters, and an optional array

2. Declare your optional parameters as local variables

3. The crux: replace the value of any optional parameters that you have passed via the array, using PHP's facility to interpret variable variable names. This line is identical for every function

4. Call the function, passing its mandatory parameters, and only those optional parameters that you require

For example,

function test_params($a, $b, $arrOptionalParams = array()) {

$c = 'sat';

$d = 'mat';

foreach($arrOptionalParams as $key => $value) ${$key} = $value;

echo "$a $b $c on the $d";

}

and then call it like this

test_params('The', 'dog', array('c' => 'stood', 'd' => 'donkey'));

test_params('The', 'cat', array('d' => 'donkey'));

test_params('A', 'dog', array('c' => 'stood'));

Results:

The dog stood on the donkey

The cat sat on the donkey

A dog stood on the mat

[#3]

rich at richware dot net [2015-05-08 17:27:17]

How to pass a class as an argument? This is simple:

class TMath {

private $_Total;

function Sum() {

$this->_Total = 0;

foreach (func_get_args() as $n) {

$this->_Total += $n;

}

}

function Total() {

return $this->_Total;

}

}

$myMath = new TMath();

$myMath->Sum(1,2,3);

ShowTotal($myMath);

function ShowTotal($aMath) {

echo $aMath->Total().'
';

}

[#4]

php at richardneill dot org [2015-03-28 19:24:09]

To experiment on performance of pass-by-reference and pass-by-value, I used this  script. Conclusions are below.

#!/usr/bin/php

for ($i=0;$i<2;$i++){#$array[$i]++;        //Uncomment this line to modify the array within the function.$sum+=$array[$i];

}

return ($sum);

}$max=1E7//10 M data points.$data=range(0,$max,1);$start=microtime(true);

for ($x=0;$x<100;$x++){$sum=sum($data,$max);

}$end=microtime(true);

echo"Time: ".($end-$start)." s\n";?>

[#5]

lucas dot ekrause at gmail dot com [2014-06-18 08:40:43]

In addition to jcaplan@bogus.amazon.com??s comment (http://www.php.net/manual/de/functions.arguments.php#62803) you could also simply write

functiong($x=null){for($i=0;$i<2;$i++){call_user_func_array("f", !is_null($x) ? array($x) : array());}}?>

[#6]

aasasdasdf at yandex dot ru [2014-04-12 12:34:22]

As of PHP 5.5.10, it seems that a variable will be separated from its value if defined right in a function call:

php > error_reporting(E_ALL);

php > function a(&$b) {$b = 1;}

php > a($q = 2); var_dump($q);

Strict Standards: Only variables should be passed by reference in php shell code on line 1

int(2)

php > $w = 3; a($w); var_dump($w);

int(1)

Notice that it's still fine to use a variable that is not defined at all:

php > a($e); var_dump($e);

int(1)

[#7]

Horst Schirmeier [2014-01-08 11:58:51]

Editor's note: what is expected here by the parser is a non-evaluated expression. An operand and two constants requires evaluation, which is not done by the parser. However, this feature is included as of PHP 5.6.0. See this page for more information: http://php.net/migration56.new-features#migration56.new-features.const-scalar-exprs

--------

"The default value must be a constant expression" is misleading (or even wrong).  PHP 5.4.4 fails to parse this function definition:

function htmlspecialchars_latin1($s, $flags = ENT_COMPAT | ENT_HTML401) {}

This yields a " PHP Parse error:  syntax error, unexpected '|', expecting ')' " although ENT_COMPAT|ENT_HTML401 is certainly what a compiler-affine person would call a "constant expression".

The obvious workaround is to use a single special value ($flags = NULL) as the default, and to set it to the desired value in the function's body (if ($flags === NULL) { $flags = ENT_COMPAT | ENT_HTML401; }).

[#8]

post at auge8472 dot de [2013-07-18 20:48:47]

I needed a way to decide between two possible values for one function parameter. I didn't want to decide it before calling the function but wanted to do the constraint inside the function call.

$foo = 1;

$bar = 2;

function foobar($val) {

echo $val;

}

foobar(isset($foo) ? $foo : $bar);

// output: 1

$bar = 2;

function foobar($val) {

echo $val;

}

foobar(isset($foo) ? $foo : $bar);

// output: 2

[#9]

ravenswd at gmail dot com [2013-07-08 14:30:14]

Be careful when passing arguments by reference, it can cause unexpected side-effects if one is not careful.

I had a program designed to sweep through directories and subdirectories and report on the total number of files, and the total size of all files. Since it needed to return two values, I used variables passed by reference.

In one spot in the program, I didn't need the values of those variables after they were returned, so I just used a garbage variable named $ignore instead. This caused a curious bug which took me a while to track down, because the effects of the bug were in a different part of the program than the place where I had made a mistake.

Since the same variable was used for both parameters passed by reference, they ended up both pointing to the same physical location in memory, so changing one of them caused both of them to change. The code below is an excerpt of my program, stripped down to just the few lines necessary to illustrate what was happening:

sweep($ignore,$ignore);// no errors occur herefunctionsweep( &$filecount, &$bytecount) {$filecount=1;$bytecount=1024;

print"Files:$filecount- Size:$bytecount";// prints "Files: 1024 - Size: 1024"}?>

[#10]

jacob at jacobweber dot com [2011-06-13 14:05:56]

This page states:

"Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected."

There seems to be one exception to this. Say you're using type-hinting for an argument, but you want to allow it to be NULL, and you want additional required arguments to the right of it. PHP allows this, as long as you give it the type-hinted argument a default value of NULL. For example:

}sample(newClassA(),'');// successsample(newClassB(),'');// failure; wrong typesample(NULL,'');// successsample(newClassA());// failure; missing second argument?>

[#11]

carlos at wfmh dot org dot pl dot REMOVE dot COM [2010-06-15 04:48:44]

You can use (very) limited signatures for your functions, specifing type of arguments allowed.

For example:

public function Right( My_Class $a, array $b )

tells first argument have to by object of My_Class, second an array. My_Class means that you can pass also object of class that either extends My_Class or implements (if My_Class is abstract class) My_Class. If you need exactly My_Class you need to either make it final, or add some code to check what $a really.

Also note, that (unfortunately) "array" is the only built-in type you can use in signature. Any other types i.e.:

public function Wrong( string $a, boolean $b )

will cause an error, because PHP will complain that $a is not an *object* of class string (and $b is not an object of class boolean).

So if you need to know if $a is a string or $b bool, you need to write some code in your function body and i.e. throw exception if you detect type mismatch (or you can try to cast if it's doable).

[#12]

rburnap at intelligent dash imaging dot com [2010-05-13 17:19:17]

This may be helpful when you need to call an arbitrary function known only at runtime:

You can call a function as a variable name.

echo"\nfoo()";

}

functioncallfunc($x,$y='')

{

if($y=='')

{

if($x=='')

echo"\nempty";

else$x();

}

else$y->$x();

}

classcbar{

public functionfcatch(){ echo"\nfcatch"; }

}$x='';callfunc($x);$x='foo';callfunc($x);$o= newcbar();$x='fcatch';callfunc($x,$o);

echo"\n\n";?>

The code will output

empty

foo()

fcatch

[#13]

mracky at pacbell dot net [2010-03-29 09:40:49]

Nothing was written here about argument types as part of the function definition.

When working with classes, the class name can be used as argument type.  This acts as a reminder to the user of the class, as well as a prototype for php  control. (At least in php 5 -- did not check 4).

public$data;

public function__construct($dd)

{$this->data=$dd;

}

};

classtest{

public$bar;

public function__construct(foo $arg)// Strict typing for argument{$this->bar=$arg;

}

public functiondump()

{

echo$this->bar->data."\n";

}

};$A= newfoo(25);$Test1= newtest($A);$Test1->dump();$Test2= newtest(10);// wrong argument for testing?>

outputs:

25

PHP Fatal error:  Argument 1 passed to test::__construct() must be an object of class foo, called in testArgType.php on line 27 and defined in testArgType.php on line 13

[#14]

pigiman at gmail dot com [2010-03-23 09:37:11]

Hey,

I started to learn for the Zend Certificate exam a few days ago and I got stuck with one unanswered-well question.

This is the question:

??Absent any actual need for choosing one method over the other, does passing arrays by value to a read-only function reduce performance compared to passing them by reference???

This question answered by Zend support team at Zend.com:

"A copy of the original $array is created within the function scope. Once the function terminates, the scope is removed and the copy of $array with it." (By massimilianoc)

Have a nice day!

Shaked KO

[#15]

allankelly at gmail dot com [2009-03-21 14:34:38]

I like to pass an associative array as an argument. This is reminiscent of a Perl technique and can be tested with is_array. For example:

{$class='';$text='';

if(is_array($opt) )

{

foreach($optas$k=>$v)

{

switch($k)

{

case'class':$class="class = '$v'";

break;

case'text':$text=$v;

break;

}

}

}

else

{$text=$opt;

}

return"

$text
";

}?>

[#16]

herenvardoREMOVEatSTUFFgmailINdotCAPScom [2009-01-17 12:48:55]

There is a nice trick to emulate variables/function calls/etc as default values:

$myVar="Using a variable as a default value!";

functionmyFunction($myArgument=null) {

if($myArgument===null)$myArgument=$GLOBALS["myVar"];

echo$myArgument;

}// Outputs "Hello World!":myFunction("Hello World!");// Outputs "Using a variable as a default value!":myFunction();// Outputs the same again:myFunction(null);// Outputs "Changing the variable affects the function!":$myVar="Changing the variable affects the function!";myFunction();?>

In general, you define the default value as null (or whatever constant you like), and then check for that value at the start of the function, computing the actual default if needed, before using the argument for actual work.

Building upon this, it's also easy to provide fallback behaviors when the argument given is not valid: simply put a default that is known to be invalid in the prototype, and then check for general validity instead of a specific value: if the argument is not valid (either not given, so the default is used, or an invalid value was given), the function computes a (valid) default to use.

[#17]

Don dot hosek at gmail dot com [2007-11-20 17:50:31]

Actually the use of class or global constants does buy us something. It helps enforce the DRY (don't repeat yourself) principle.

[#18]

conciseusa at yahoo[nospammm] dot com [2007-04-22 20:03:49]

With regards to:

It is also possible to force a parameter type using this syntax. I couldn't see it in the documentation.

function foo(myclass par) { }

I think you are referring to Type Hinting. It is documented here: http://ch2.php.net/language.oop5.typehinting

[#19]

pdenny at magmic dot com [2007-02-18 09:43:09]

Note that constants can also be used as default argument values

so the following code:

define('TEST_CONSTANT','Works!');

function testThis($var=TEST_CONSTANT) {

echo "Passing constants as default values $var";

}

testThis();

will produce :

Passing constants as default values Works!

(I tried this in both PHP 4 and 5)

[#20]

John [2006-11-15 15:20:50]

This might be documented somewhere OR obvious to most, but when passing an argument by reference (as of PHP 5.04) you can assign a value to an argument variable in the function call. For example:

function my_function($arg1, &$arg2) {

if ($arg1 == true) {

$arg2 = true;

}

}

my_function(true, $arg2 = false);

echo $arg2;

outputs 1 (true)

my_function(false, $arg2 = false);

echo $arg2;

outputs 0 (false)

[#21]

keuleu at hotmail dot com [2006-10-19 02:59:39]

I ran into the problem that jcaplan mentionned. I had just finished building 2 handler classes and one interface.

During my testing I realized that my handlers were not initializing their variables to their default values when my interface was calling them with 'null' values:

this is a simplified illustration:

echo$v1.',  ';

echo$v2.',  ';

echo$v3;

}some_function();//this will behave as expected, displaying 'value1,  value2,  value3'some_function(null,null,null);//this on the other hand will display ',  ,' since the variables will take the null value.?>

I came to about the same conclusion as jcaplan. To force your function parameters to take a default value when a null is passed you need to include a conditionnal assignment inside the function definition.

echo$v1;

echo$v2;

echo$v3;

}?>

[#22]

jcaplan at bogus dot amazon dot com [2006-03-09 15:11:02]

In function calls, PHP clearly distinguishes between missing arguments and present but empty arguments.  Thus:

The utility of the optional argument feature is thus somewhat diminished.  Suppose you want to call the function f many times from function g, allowing the caller of g to specify if f should be called with a specific value or with its default value:

Both options suck.

The best approach, it seems to me, is to always use a sentinel like null as the default value of an optional argument.  This way, callers like g and g's clients have many options, and furthermore, callers always know how to omit arguments so they can omit one in the middle of the parameter list.

functiong($x=null) {f($x);f($x); }f();// prints 4f(null);// prints 4f($y);// $y undefined, prints 4g();// prints 4 twiceg(null);// prints 4 twiceg(5);// prints 5 twice?>

[#23]

ksamvel at gmail dot com [2006-02-07 07:55:07]

by default Classes constructor does not have any arguments. Using small trick with func_get_args() and other relative functions constructor becomes a function w/ args (tested in php 5.1.2). Check it out:

class A {

public function __construct() {

echo func_num_args() . "
";

var_dump( func_get_args());

echo "
";

}

}

$oA = new A();

$oA = new A( 1, 2, 3, "txt");

Output:

0

array(0) { }

4

array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> string(3) "txt" }

[#24]

Sergio Santana: ssantana at tlaloc dot imta dot mx [2005-10-31 14:59:12]

PASSING A "VARIABLE-LENGTH ARGUMENT LIST OF REFERENCES" TO A FUNCTION

As of PHP 5, Call-time pass-by-reference has been deprecated, this represents no problem in most cases, since instead of calling a function like this:

myfunction($arg1, &$arg2, &$arg3);

you can call it

myfunction($arg1, $arg2, $arg3);

provided you have defined your function as

function myfuncion($a1, &$a2, &$a3) { // so &$a2 and &$a3 are

// declared to be refs.

... 

}

However, what happens if you wanted to pass an undefined number of references, i.e., something like:

myfunction(&$arg1, &$arg2, ..., &$arg-n);?

This doesn't work in PHP 5 anymore.

In the following code I tried to amend this by using the

array() language-construct as the actual argument in the

call to the function.

// "pseudo-argument" by 2sforeach ($Aas &$x) {$x+=2;

}

}$x=1;$y=2;$z=3;aa(array(&$x, &$y, &$z));

echo"--$x--$y--$z--\n";// This will output:

// --3--4--5--?>

I hope this is useful.

Sergio.

[#25]

grinslives13 at hotmail dot com~=s/i/ee/g [2005-09-24 22:55:17]

Given that we have two coding styles:

#

# Code (A)

#

funtion foo_a (&$var)

{

$var *= 2;

return $var;

}

foo_a($a);

#

# Code (B)

#

function foo_b ($var)

{

$var *= 2;

return $var;

}

foo_b(&$a);

I personally wouldn't recommend (B) - I think it strange why php would support such a convention as it would have violated foo_b's design - its use would not do justice to its function prototype. And thinking about such use, I might have to think about copying all variables instead of working directly on them...

Coding that respects function prototypes strictly would, I believe, result in code that is more intuitive to read. Of course, in php <=4, not being able to use default values with references, we can't do this that we can do in C:

#

# optional return-value parameters

#

int foo_c (int var, int *ret)

{

var *= 2;

if (ret) *ret = var;

return var;

}

foo_c(2, NULL);

Of course, since variables are "free" anyway, we can always get away with it by using dummy variables...

zlel

[#26]

nate at natemurray dot com [2005-08-30 15:15:31]

Of course you can fake a global variable for a default argument by something like this:

<?phpfunctionself_url ($text,$page,$per_page=NULL) {$per_page= ($per_page==NULL) ?$GLOBALS['gPER_PAGE'] :$per_page;# setup a default value of per pagereturnsprintf("%s",$_SERVER["PHP_SELF"],$page,$per_page,$text);

}?>

[#27]

Angelina Bell [2005-07-25 12:40:09]

It is so easy to create a constant that the php novice might do so accidently while attempting to call a function with no arguments.  For example:

returntrue;

}

functionSessionCheck(){blah blah blah;// check for session timeout...

if ($timeout)LogoutUser;// should be LogoutUser();}?>

OOPS!  I don't notice my typo, the SessionCheck function

doesn't work, and it takes me all afternoon to figure out why not!

LogoutUser;

print"new constant LogoutUser is ".LogoutUser;?>

[#28]

balint , at ./ atres &*( ath !# cx [2005-06-30 02:59:49]

(in reply to benk at NOSPAM dot icarz dot com / 24-Jun-2005 04:21)

I could make use of this assignment, as below, to have a permanently existing, but changing data block (because it is used by many other classes), where the order or the refreshed contents are needed for the others: (DB init done by one, an other changed the DB, and thereafter all others need to use the other DB without creating new instances, or creating a log array in one, and we would like to append the new debug strings to the array, atmany places.)

class xyz {

var argN = array();

function xyz($argN) {

$this->argN = &$argN;

}

function etc($text) {

array_push($this->argN, $text);

}

}

class abc {

var argM = array();

function abc($argM) {

$this->argM = &$argM;

}

function etc($text) {

array_push($this->argM, $text);

}

}

$messages=array("one", "two");

$x = new xyz(&$messages);

$x->etc("test");

$a = new abc(&$messages);

$a->etc("tset");

...

[#29]

csaba at alum dot mit dot edu [2005-01-26 04:58:11]

Argument evaluation left to right means that you can save yourself a temporary variable in the example below whereas $current = $prior + ($prior=$current) is just the same as $current *= 2;

function Sum() { return array_sum(func_get_args()); }

function Fib($n,$current=1,$prior=0) {

for (;--$n;) $current = Sum($prior,$prior=$current);

return $current;

}

Csaba Gabor

PS.  You could, of course, just use array_sum(array(...)) in place of Sum(...)

[#30]

heck AT fas DOT harvard DOT edu [2004-03-24 17:49:49]

I have some functions that I'd like to be able to pass arguments two ways: Either as an argument list of variable length (e.g. func(1, 2, 3, 4)) or as an array (e.g., func(array(1,2,3,4)). Only the latter can be constructed on the fly (e.g., func($ar)), but the syntax of the former can be neater.

The way to do it is to begin the function as follows:

$args = func_get_args();

if (is_array ($args[0]))

$args = $args[0];

Then one can just use $args as the list of arguments.

[#31]

thesibster at hotmail dot com [2003-06-30 11:43:27]

Call-time pass-by-ref arguments are deprecated and may not be supported later, so doing this:

----

function foo($str) {

$str = "bar";

}

$mystr = "hello world";

foo(&$mystr);

----

will produce a warning when using the recommended php.ini file.  The way I ended up using for optional pass-by-ref args is to just pass an unused variable when you don't want to use the resulting parameter value:

----

function foo(&$str) {

$str = "bar";

}

foo($_unused_);

----

Note that trying to pass a value of NULL will produce an error.

[#32]

guillaume dot goutaudier at eurecom dot fr [2002-07-19 12:15:33]

Concerning default values for arguments passed by reference:

I often use that trick:

func($ref=$defaultValue) {

$ref = "new value";

}

func(&$var);

print($var) // echo "new value"

Setting $defaultValue to null enables you to write functions with optional arguments which, if given, are to be modified.

[#33]

wls at wwco dot com [2001-11-20 11:29:08]

Follow up to resource passing:

It appears that if you have defined the resource in the same file

as the function that uses it, you can get away with the global trick.

Here's the failure case:

include "functions_doing_globals.php"

$conn = openDatabaseConnection();

invoke_function_doing_global_conn();

...that it fails.

Perhaps it's some strange scoping problem with include/require, or

globals trying to resolve before the variable is defined, rather

than at function execution.

[#34]

rwillmann at nocomment dot sk [2001-06-21 15:05:20]

There is no way how to deal with calling by reference when variable lengths argument list are passed.


Only solutions is to use construction like this:

function foo($args) {

...

}

foo(array(&$first, &$second));

Above example pass by value a list of references to other variables :-)

It is courios, becouse when you call a function with arguments passed via &$parameter syntax, func_get_args returns array of copies :-(

rwi

[#35]

artiebob at go dot com [2001-02-25 13:48:33]

here is the code to pass a user defined function as an argument.  Just like in the usort method.

func2("func1");

functionfunc1($arg){

print ("Hello$arg");

}

functionfunc2($arg1){$arg1("World");//Does the same thing as the next linecall_user_func($arg1,"World");

}?>

[#36]

david at petshelter dot net [2001-01-24 23:23:38]

With reference to the note about extract() by dietricha@subpop.com:

He is correct and this is great!  What he does not say explicitly is that the extracted variable names have the scope of the function, not the global namespace.  (This is the appropriate behavior IMO.)  If for some reason you want the extracted variables to be visible in the global namespace, you must declare them 'global' inside the function.

[#37]

coop at better-mouse-trap dot com [2000-10-09 20:59:37]

If you prefer to use named arguments to your functions (so you don't have to worry about the order of variable argument lists), you can do so PERL style with anonymous arrays:

{

print"named_arg1 : ".$args["named_arg1"] ."\n";

print"named_arg2 : ".$args["named_arg2"] ."\n";

}foo(array("named_arg1"=>"arg1_value","named_arg2"=>"arg2_value"));?>

will output:

named_arg1 : arg1_value

named_arg2 : arg2_value

[#38]

almasy at axisdata dot com [2000-08-20 16:11:13]

Re: Passing By Reference Inside A Class

Passing arguments by reference does work inside a class.  When you do:

$this->testVar = $ref;

inside setTestVar(), you're copying by value instead of copying by reference.  I think what you want there is this:

$this->testVar = &$ref;

Which is the new "assign by reference" syntax that was added in PHP4.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值