update : 2015.11.03
php.shukuma.com

검색:
 
 
함수 인수

함수 인수

함수 인수를 통해서 함수에 정보를 넘겨줄수 있다. 이런 함수 인수는 콤마(,)로 구별되는 표현 목록이다.

PHP는 값에 의한 인수 전달(passing by value) (기본값), 참조에 의한 전달, 인수 기본값 기능을 지원합니다. 가변 길이 인수 목록도 지원하며, 자세한 정보는 func_num_args(), func_get_arg(), func_get_args() 함수 레퍼런스를 참고하십시오.

Example #1 함수에 배열 넘겨주기

<?php
function takes_array($input)
{
    echo 
"$input[0] + $input[1] = "$input[0]+$input[1];
}
?>

참조에 의한 인수 전달하기

기본적으로, 함수 인수는 값에 의해 전달됩니다. (그래서 함수내의 인수 변수값을 변경해도 함수 밖에서는 바뀌지 않습니다) 함수가 그 인수를 바꾸게 하려면, 참조로 넘겨줘야 합니다.

항상 함수의 인수를 참조로 넘기게 하려면, 함수 정의에서 엠퍼샌드(&)를 인수 이름 앞에 붙이면 됩니다:

Example #2 참조에 의해 함수 인수 전달하기

<?php
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.'
?>

기본 인수 값

함수는 다음과 같이 스칼라 인수에 대해 C++스타일 기본값으로 지정할수있다:

Example #3 함수에 기본 인수 사용하기

<?php
function makecoffee($type "cappuccino")
{
    return 
"Making a cup of $type.\n";
}
echo 
makecoffee();
echo 
makecoffee(null);
echo 
makecoffee("espresso");
?>

위 예제의 출력:

Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

PHP는 array와 특별형 NULL을 기본값으로 사용할 수 있습니다. 예를 들면:

Example #4 스칼라 형이 아닌 기본값 사용하기

<?php
function makecoffee($types = array("카푸치노"), $coffeeMaker NULL)
{
    
$device is_null($coffeeMaker) ? "손" $coffeeMaker;
    return 
"$device(으)로 ".join(", "$types)."를 만듭니다.\n";
}
echo 
makecoffee();
echo 
makecoffee(array("카푸치노""라바짜"), "찻주전자");
?>

기본값은 상수 표현식이 될수 있으나 (예를 들면) 변수나 클래스 멤버가 될수는 없다.

기본 인수를 사용할때에는 모든 기본값은 기본값을 쓰지 않는 인수의 오른쪽으로 가야 한다; 그렇지 않으면, 기대하던대로 작동하지 않을것이다. 다음 예제 코드를 참고:

Example #5 기본 함수 인수가 잘못 사용된 예

<?php
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/phptest/functest.html on line 41
Making a bowl of raspberry .

위 코드를 아래 코드와 비교하라:

Example #6 기본 함수 인수의 정확한 사용예

<?php
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.

Note: PHP 5부터, 기본값을 참조로 넘길 수 있습니다.

Type declarations

Note:

Type declarations were also known as type hints in PHP 5.

Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.

To specify a type declaration, the type name should be added before the parameter name. The declaration can be made to accept NULL values if the default value of the parameter is set to NULL.

Valid types

Type Description Minimum PHP version
Class/interface name The parameter must be an instanceof the given class or interface name. PHP 5.0.0
self The parameter must be an instanceof the same class as the one the method is defined on. This can only be used on class and instance methods. PHP 5.0.0
array The parameter must be an array. PHP 5.1.0
callable The parameter must be a valid callable. PHP 5.4.0
bool The parameter must be a boolean value. PHP 7.0.0
float The parameter must be a floating point number. PHP 7.0.0
int The parameter must be an integer. PHP 7.0.0
string The parameter must be a string. PHP 7.0.0

예제

Example #7 Basic class type declaration

<?php
class {}
class 
extends {}

// This doesn't extend C.
class {}

function 
f(C $c) {
    echo 
get_class($c)."\n";
}

f(new C);
f(new D);
f(new E);
?>

위 예제의 출력:

C
D

Fatal error: Uncaught TypeError: Argument 1 passed to f() must be an instance of C, instance of E given, called in - on line 14 and defined in -:8
Stack trace:
#0 -(14): f(Object(E))
#1 {main}
  thrown in - on line 8

Example #8 Basic interface type declaration

<?php
interface { public function f(); }
class 
implements { public function f() {} }

// This doesn't implement I.
class {}

function 
f(I $i) {
    echo 
get_class($i)."\n";
}

f(new C);
f(new E);
?>

위 예제의 출력:

C

Fatal error: Uncaught TypeError: Argument 1 passed to f() must implement interface I, instance of E given, called in - on line 13 and defined in -:8
Stack trace:
#0 -(13): f(Object(E))
#1 {main}
  thrown in - on line 8

Example #9 Nullable type declaration

<?php
class {}

function 
f(C $c null) {
    
var_dump($c);
}

f(new C);
f(null);
?>

위 예제의 출력:

object(C)#1 (0) {
}
NULL

Strict typing

By default, PHP will coerce values of the wrong type into the expected scalar type if possible. For example, a function that is given an integer for a parameter that expects a string will get a variable of type string.

It is possible to enable strict mode on a per-file basis. In strict mode, only a variable of exact type of the type declaration will be accepted, or a TypeError will be thrown. The only exception to this rule is that an integer may be given to a function expecting a float.

To enable strict mode, the declare statement is used with the strict_types declaration:

Caution

Enabling strict mode will also affect return type declarations.

Note:

Strict typing applies to function calls made from within the file with strict typing enabled, not to the functions declared within that file. If a file without strict typing enabled makes a call to a function that was defined in a file with strict typing, the caller's preference (weak typing) will be respected, and the value will be coerced.

Note:

Strict typing is only defined for scalar type declarations, and as such, requires PHP 7.0.0 or later, as scalar type declarations were added in that version.

Example #10 Strict typing

<?php
declare(strict_types=1);

function 
sum(int $aint $b) {
    return 
$a $b;
}

var_dump(sum(12));
var_dump(sum(1.52.5));
?>

위 예제의 출력:

int(3)

Fatal error: Uncaught TypeError: Argument 1 passed to sum() must be of the type integer, float given, called in - on line 9 and defined in -:4
Stack trace:
#0 -(9): sum(1.5, 2.5)
#1 {main}
  thrown in - on line 4

Example #11 Weak typing

<?php
function sum(int $aint $b) {
    return 
$a $b;
}

var_dump(sum(12));

// These will be coerced to integers: note the output below!
var_dump(sum(1.52.5));
?>

위 예제의 출력:

int(3)
int(3)

Example #12 Catching TypeError

<?php
declare(strict_types=1);

function 
sum(int $aint $b) {
    return 
$a $b;
}

try {
    
var_dump(sum(12));
    
var_dump(sum(1.52.5));
} catch (
TypeError $e) {
    echo 
'Error: '.$e->getMessage();
}
?>

위 예제의 출력:

int(3)
Error: Argument 1 passed to sum() must be of the type integer, float given, called in - on line 10

가변 길이 인수 목록

PHP는 사용자 선언 함수에서 가변 길이 인수 목록을 지원합니다. PHP 5.6 이상에서는 ... 토큰을 사용하고, PHP 5.5 이하에서는 func_num_args(), func_get_arg(), func_get_args() 함수를 사용합니다.

PHP 5.6+에서 ...

PHP 5.6 이상에서, 인수 목록은 ... 토큰을 포함하여 함수가 가변 수의 인수를 받을 수 있다고 표시할 수 있습니다. 인수는 배열로 주어진 변수에 전달됩니다; 예제:

Example #13 가변 인수에 접근하기 위한 ... 사용하기

<?php
function sum(...$numbers) {
    
$acc 0;
    foreach (
$numbers as $n) {
        
$acc += $n;
    }
    return 
$acc;
}

echo 
sum(1234);
?>

위 예제의 출력:

10

또한 함수를 호출할 때 ...을 사용하여 array, Traversable 변수, 또는 literal을 인수 목록에 포함할 수 있습니다. literal into the argument list:

Example #14 인수 제공을 위한 ... 사용하기

<?php
function add($a$b) {
    return 
$a $b;
}

echo 
add(...[12])."\n";

$a = [12];
echo 
add(...$a);
?>

위 예제의 출력:

3
3

보통의 위치 인수를 ... 앞에 지정할 수 있습니다. 이 경우, 위치 인수에 어울리지 않는 인수만이 ...로 생성되는 배열에 추가됩니다.

... 토큰 앞에 type hint를 추가할 수 있습니다. 이 정보가 존재할 경우, ...에 들어가는 모든 인수는 해당 클래스의 객체여야 합니다.

Example #15 Type hinted variable arguments

<?php
function total_intervals($unitDateInterval ...$intervals) {
    
$time 0;
    foreach (
$intervals as $interval) {
        
$time += $interval->$unit;
    }
    return 
$time;
}

$a = new DateInterval('P1D');
$b = new DateInterval('P2D');
echo 
total_intervals('d'$a$b).' days';

// This will fail, since null isn't a DateInterval object.
echo total_intervals('d'null);
?>

위 예제의 출력:

3 days
Catchable fatal error: Argument 2 passed to total_intervals() must be an instance of DateInterval, null given, called in - on line 14 and defined in - on line 2

마지막으로, ... 앞에 앰퍼샌드를 붙여서(&) 가변 인수를 참조로 전달할 수 있습니다.

PHP 구 버전

가변 인수로 만들기 위한 특별한 문법은 필요하지 않습니다; 하지만 함수의 인수에 접근하려면 func_num_args(), func_get_arg(), func_get_args() 함수를 사용해야 합니다.

위 예제 중 첫번째를 PHP 5.5 이전에서는 다음과 같이 사용합니다:

Example #16 PHP 5.5 이전의 가변 길이 인수 접근하기

<?php
function sum() {
    
$acc 0;
    foreach (
func_get_args() as $n) {
        
$acc += $n;
    }
    return 
$acc;
}

echo 
sum(1234);
?>

위 예제의 출력:

10