Function arguments

argument list를 통해 함수에 어떤 정보를 넘겨줄 수 있다. 이 argument list는 쉼표(,)로 나뉘어진 변수나 상수의 list이다.

PHP는 passing by value(기본적으로 이것을 사용)와 passing by reference, default argument values의 3가지 방법을 제공한다. 가변 길이(Variable-length) argument list는 PHP4이후에서만 제공된다. 자세한 내용은 Variable-length argument listsfunc_num_args(), func_get_arg(), func_get_args() 함수의 설명을 보기 바란다. 그러나 PHP3에서도 배열을 통한 전달을 사용한다면 비슷한 효과를 낼 수 있다.

function takes_array($input) {
    echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}

Making arguments be passed by reference

기본값으로 함수의 인수(argument)들은 값으로 전달된다(passed by value). 함수내에서 변화시킨 값을 함수 밖에서도 적용시키려면 pass by reference로 인수를 넘겨야 한다.

어떤 함수의 인수를 항상 pass by reference로 넘기려 한다면, 함수를 선언할 때 ampersand(&)를 인수의 앞에 붙여주면 된다. :

function add_some_extra(&$string) {
    $string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'

만약 기본값은 by value 로 하지만 필요에 따라 by reference로 호출하고 싶다면 함수 호출 시에 인수의 앞에 &를 붙이면 된다. :

function foo ($bar) {
    $bar .= ' and something extra.';
}
$str = 'This is a string, ';
foo ($str);
echo $str;    // outputs 'This is a string, '
foo (&$str);
echo $str;    // outputs 'This is a string, and something extra.'

Default argument values

스칼라 인수(argument)에 대해서는 다음과 같이 C++ 과 비슷하게 기본값을 정해줄 수 있다. :

function makecoffee ($type = "cappucino") {
    return "Making a cup of $type.\n";
}
echo makecoffee ();
echo makecoffee ("espresso");

위의 코드의 실행 결과는 다음과 같다 :
Making a cup of cappucino.
Making a cup of espresso.

default 값은 반드시 상수이어야 한다. (예를들어) 변수나 class의 멤버를 사용해서는 안된다.

default argument를 사용할 때, default가 되는 인수들은 non-default인 인수들보다 오른쪽에 위치해야 한다. 그렇지 않으면 원하는 결과가 나오지 않는다. 다음을 보자. :

function makeyogurt ($type = "acidophilus", $flavour) {
    return "Making a bowl of $type $flavour.\n";
}
 
echo makeyogurt ("raspberry");   // won't work as expected

위 코드의 실행 결과는 다음과 같다 :
Warning: Missing argument 2 in call to makeyogurt() in 
/usr/local/etc/httpd/htdocs/php3test/functest.html on line 41
Making a bowl of raspberry .

그러면 이제 위의 것과 아래것을 비교해 보자. :

function makeyogurt ($flavour, $type = "acidophilus") {
    return "Making a bowl of $type $flavour.\n";
}
 
echo makeyogurt ("raspberry");   // works as expected

이 예제의 실행 결과는 다음과 같다. :
Making a bowl of acidophilus raspberry.

Variable-length argument lists

PHP4에서는 사용자 정의 함수에 가변 길이(Variable-length) argument list를 제공한다. func_num_args(), func_get_arg(), func_get_args() 함수를 사용하여 쉽게 사용할 수 있다.

특별한 문법이 사용되지도 않고, 함수의 정의시나 사용시 argument list는 보통의 경우와 동일하게 사용하면 된다.