라이브러리

[PHP] Yac::__get - 게터




Yac::__get 이란?

Yac (Yet Another Class) 는 PHP 의 내장 클래스 중 하나로, PHP 7.4 부터 사용할 수 있습니다. Yac::__get 메소드는 PHP 클래스의 속성을 동적으로 읽는 방법을 제공합니다.

Yac::__get 사용법

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

#hostingforum.kr
php

class MyClass {

    private $myProperty;



    public function __get($name) {

        if ($name === 'myProperty') {

            return $this->myProperty;

        } else {

            throw new Exception("Undefined property: $name");

        }

    }

}



위 예제에서, `MyClass` 클래스의 `$myProperty` 속성을 읽으려면 `$obj->myProperty` 형식으로 접근할 수 있습니다.

#hostingforum.kr
php

$obj = new MyClass();

$obj->myProperty = 'Hello, World!';

echo $obj->myProperty; // 출력: Hello, World!



Yac::__get 예제

다음 예제에서는 Yac::__get 메소드를 사용하여 동적으로 속성을 읽는 방법을 보여줍니다.

#hostingforum.kr
php

class MyClass {

    private $myProperties = [

        'name' => 'John Doe',

        'age' => 30,

    ];



    public function __get($name) {

        if (array_key_exists($name, $this->myProperties)) {

            return $this->myProperties[$name];

        } else {

            throw new Exception("Undefined property: $name");

        }

    }

}



$obj = new MyClass();

echo $obj->name; // 출력: John Doe

echo $obj->age; // 출력: 30

try {

    echo $obj->nonExistentProperty;

} catch (Exception $e) {

    echo $e->getMessage(); // 출력: Undefined property: nonExistentProperty

}



위 예제에서, `MyClass` 클래스의 `$myProperties` 배열을 읽으려면 `$obj->name` 또는 `$obj->age` 형식으로 접근할 수 있습니다. `nonExistentProperty` 속성이 존재하지 않으므로 예외가 발생합니다.

Yac::__get 사용 시 주의점

Yac::__get 메소드를 사용할 때 주의해야 할 점은 다음과 같습니다.

* 속성이 존재하지 않으면 예외가 발생하므로, 존재하지 않는 속성을 읽으려는 경우 예외를 처리해야 합니다.
* 속성이 존재하지 않더라도 예외를 발생시키지 않으려면 `__get` 메소드에서 `return null` 또는 `return ''`과 같은 값을 반환할 수 있습니다.

#hostingforum.kr
php

class MyClass {

    private $myProperties = [

        'name' => 'John Doe',

        'age' => 30,

    ];



    public function __get($name) {

        if (array_key_exists($name, $this->myProperties)) {

            return $this->myProperties[$name];

        } else {

            return null; // 또는 return '';

        }

    }

}



위 예제에서, `MyClass` 클래스의 `$myProperties` 배열의 속성이 존재하지 않더라도 예외를 발생시키지 않습니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

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

검색

게시물 검색