라이브러리

[PHP] Closure::fromCallable - 호출 가능한 객체를 클로저로 변환합니다.




Closure::fromCallable


PHP 8.0 버전부터 Closure 클래스에 `fromCallable` 메소드가 추가되었습니다. 이 메소드는 callable 형식의 값을 받아서 Closure 객체를 반환합니다.

# 사용법


`fromCallable` 메소드는 다음과 같은 형식으로 사용할 수 있습니다.

#hostingforum.kr
php

Closure::fromCallable(callable $callable): Closure



# 예제


#hostingforum.kr
php

// Callable 함수

function add($a, $b) {

    return $a + $b;

}



// Closure::fromCallable을 사용하여 Closure 객체를 생성

$closure = Closure::fromCallable('add');

echo $closure(5, 3); // 8



// Closure::fromCallable을 사용하여 Closure 객체를 생성 (객체 메소드)

class Calculator {

    public function add($a, $b) {

        return $a + $b;

    }

}



$calculator = new Calculator();

$closure = Closure::fromCallable([$calculator, 'add']);

echo $closure(5, 3); // 8



# Closure::fromCallable의 장점


- Closure::fromCallable을 사용하면 callable 형식의 값을 Closure 객체로 쉽게 변환할 수 있습니다.
- Closure::fromCallable을 사용하면 callable 형식의 값을 Closure 객체로 변환할 때, 타입 체크를 할 수 있습니다.

# Closure::fromCallable의 단점


- Closure::fromCallable을 사용하면 Closure 객체를 생성할 때, callable 형식의 값을 전달해야 합니다.
- Closure::fromCallable을 사용하면 Closure 객체를 생성할 때, 타입 체크를 할 수 있지만, 타입 체크를 무시할 수도 있습니다.

결론


Closure::fromCallable은 PHP 8.0 버전부터 추가된 메소드로, callable 형식의 값을 Closure 객체로 쉽게 변환할 수 있습니다. Closure::fromCallable을 사용하면 타입 체크를 할 수 있지만, 타입 체크를 무시할 수도 있습니다. 따라서 Closure::fromCallable을 사용할 때, callable 형식의 값을 전달하고 타입 체크를 하도록 하세요.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 8,985건 / 587 페이지

검색

게시물 검색