라이브러리

[PHP] ReflectionParameter::getDefaultValue - 기본 매개변수 값을 가져옵니다.




ReflectionParameter::getDefaultValue


PHP ReflectionParameter 클래스의 `getDefaultValue` 메소드는 파라미터의 기본값을 반환합니다. 이 메소드는 파라미터의 기본값을 가져올 때 유용합니다.

# 예제 1: 기본값 가져오기


#hostingforum.kr
php

class MyClass {

    public function myMethod($param = 'default') {

        echo $param . "
";

    }

}



$reflectionClass = new ReflectionClass('MyClass');

$reflectionMethod = $reflectionClass->getMethod('myMethod');

$reflectionParameter = $reflectionMethod->getParameters()[0];



echo $reflectionParameter->getName() . "
"; // param

echo $reflectionParameter->getDefaultValue() . "
"; // default



# 예제 2: 기본값이 없는 경우


#hostingforum.kr
php

class MyClass {

    public function myMethod($param) {

        echo $param . "
";

    }

}



$reflectionClass = new ReflectionClass('MyClass');

$reflectionMethod = $reflectionClass->getMethod('myMethod');

$reflectionParameter = $reflectionMethod->getParameters()[0];



echo $reflectionParameter->getName() . "
"; // param

var_dump($reflectionParameter->getDefaultValue()); // NULL



# 예제 3: 기본값이 null인 경우


#hostingforum.kr
php

class MyClass {

    public function myMethod($param = null) {

        echo $param . "
";

    }

}



$reflectionClass = new ReflectionClass('MyClass');

$reflectionMethod = $reflectionClass->getMethod('myMethod');

$reflectionParameter = $reflectionMethod->getParameters()[0];



echo $reflectionParameter->getName() . "
"; // param

var_dump($reflectionParameter->getDefaultValue()); // NULL



# 예제 4: 기본값이 배열인 경우


#hostingforum.kr
php

class MyClass {

    public function myMethod($param = ['key' => 'value']) {

        echo json_encode($param) . "
";

    }

}



$reflectionClass = new ReflectionClass('MyClass');

$reflectionMethod = $reflectionClass->getMethod('myMethod');

$reflectionParameter = $reflectionMethod->getParameters()[0];



echo $reflectionParameter->getName() . "
"; // param

var_dump($reflectionParameter->getDefaultValue()); // array(1) { ["key"]=> string(5) "value" }



# 예제 5: 기본값이 객체인 경우


#hostingforum.kr
php

class MyClass {

    public function myMethod($param = new stdClass()) {

        echo json_encode($param) . "
";

    }

}



$reflectionClass = new ReflectionClass('MyClass');

$reflectionMethod = $reflectionClass->getMethod('myMethod');

$reflectionParameter = $reflectionMethod->getParameters()[0];



echo $reflectionParameter->getName() . "
"; // param

var_dump($reflectionParameter->getDefaultValue()); // object(stdClass)#1 (0) { }



위 예제에서 `getDefaultValue` 메소드는 파라미터의 기본값을 반환합니다. 기본값이 없을 때는 NULL을 반환합니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 10,077건 / 278 페이지

검색

게시물 검색