라이브러리

[PHP] ReflectionClass::markLazyObjectAsInitialized - 초기화 프로그램이나 팩토리를 호출하지 않고 지연 객체를 초기화된 것으로 표시합니다.




ReflectionClass::markLazyObjectAsInitialized


PHP 8.1 버전부터 ReflectionClass::markLazyObjectAsInitialized 메소드가 추가되었습니다. 이 메소드는 Lazy Object를 초기화 한 후에 사용할 수 있도록 합니다.

Lazy Object는 PHP 8.1 버전부터 추가된 기능으로, 객체를 초기화하지 않고도 객체를 사용할 수 있도록 합니다. 하지만, 객체를 사용하기 전에 초기화를 해야하는 경우가 많습니다. ReflectionClass::markLazyObjectAsInitialized 메소드는 이러한 경우를 해결하기 위해 사용됩니다.

예제


#hostingforum.kr
php

class LazyObject {

    private static $instance;



    private function __construct() {

        echo "LazyObject 초기화
";

    }



    public static function getInstance() {

        if (!self::$instance) {

            self::$instance = new self();

        }

        return self::$instance;

    }

}



$reflectionClass = new ReflectionClass('LazyObject');

$obj = $reflectionClass->newInstanceWithoutConstructor();



// LazyObject 초기화가 안 된 상태

var_dump($obj instanceof LazyObject); // bool(true)



// LazyObject 초기화

$reflectionClass->markLazyObjectAsInitialized($obj);



// LazyObject 초기화가 된 상태

var_dump($obj instanceof LazyObject); // bool(true)



사용 예시


#hostingforum.kr
php

class User {

    private $name;



    public function __construct(string $name) {

        $this->name = $name;

    }



    public function getName(): string {

        return $this->name;

    }

}



class UserService {

    private $userRepository;



    public function __construct(UserRepository $userRepository) {

        $this->userRepository = $userRepository;

    }



    public function getUser(string $id): User {

        $user = $this->userRepository->getUser($id);

        if (!$user) {

            throw new Exception("User not found");

        }

        return $user;

    }

}



class UserRepository {

    private $users;



    public function __construct() {

        $this->users = [

            1 => new User("John"),

            2 => new User("Jane"),

        ];

    }



    public function getUser(int $id): ?User {

        return $this->users[$id] ?? null;

    }

}



$reflectionClass = new ReflectionClass('UserRepository');

$userRepository = $reflectionClass->newInstanceWithoutConstructor();



// UserRepository 초기화가 안 된 상태

$userService = new UserService($userRepository);



try {

    $userService->getUser(1);

} catch (Exception $e) {

    echo "User not found
";

}



// UserRepository 초기화

$reflectionClass->markLazyObjectAsInitialized($userRepository);



// UserRepository 초기화가 된 상태

$userService = new UserService($userRepository);

$user = $userService->getUser(1);

echo $user->getName(); // John



결론


ReflectionClass::markLazyObjectAsInitialized 메소드는 Lazy Object를 초기화 한 후에 사용할 수 있도록 합니다. 이 메소드는 PHP 8.1 버전부터 추가되었습니다. 예제를 통해 Lazy Object의 초기화와 사용 방법을 설명했습니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

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

검색

게시물 검색