라이브러리
[PHP] ReflectionClass::isIterable - 이 클래스가 반복 가능한지 확인합니다.
ReflectionClass::isIterable
PHP 7.1 버전부터 ReflectionClass::isIterable 메소드가 추가되었습니다. 이 메소드는 클래스가 반복 가능한지 여부를 확인하는 데 사용됩니다. 반복 가능하다는 것은 클래스의 인스턴스가 foreach 문을 사용할 수 있는지 여부를 의미합니다.
사용법
ReflectionClass::isIterable 메소드는 ReflectionClass 인스턴스를 인수로 받습니다. 이 메소드는 boolean 값을 반환하며, 클래스가 반복 가능하다면 true, 반복 불가능하다면 false를 반환합니다.
예제
#hostingforum.kr
php
// 반복 가능 클래스
class User implements IteratorAggregate
{
private $name;
private $age;
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
public function getIterator()
{
return new ArrayIterator([
'name' => $this->name,
'age' => $this->age,
]);
}
}
// 반복 불가능 클래스
class Product
{
private $name;
private $price;
public function __construct($name, $price)
{
$this->name = $name;
$this->price = $price;
}
}
// ReflectionClass 인스턴스 생성
$reflectionUser = new ReflectionClass('User');
$reflectionProduct = new ReflectionClass('Product');
// ReflectionClass::isIterable 메소드 사용
echo $reflectionUser->isIterable() ? 'true' : 'false'; // true
echo "
";
echo $reflectionProduct->isIterable() ? 'true' : 'false'; // false
참고
* 반복 가능 클래스는 IteratorAggregate 인터페이스를 구현해야 합니다.
* 반복 불가능 클래스는 반복 가능 클래스와 달리 IteratorAggregate 인터페이스를 구현하지 않습니다.
* ReflectionClass::isIterable 메소드는 클래스가 반복 가능하다는 것을 확인하는 데 사용됩니다. 반복 가능 클래스의 인스턴스를 생성하고 foreach 문을 사용하여 반복 가능 여부를 확인할 수 있습니다.
#hostingforum.kr
php
// 반복 가능 클래스 인스턴스 생성
$user = new User('John Doe', 30);
// foreach 문 사용
foreach ($user as $key => $value) {
echo "$key: $value
";
}
결론
ReflectionClass::isIterable 메소드는 클래스가 반복 가능하다는 것을 확인하는 데 사용됩니다. 반복 가능 클래스의 인스턴스를 생성하고 foreach 문을 사용하여 반복 가능 여부를 확인할 수 있습니다. 반복 불가능 클래스의 인스턴스는 foreach 문을 사용할 수 없습니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.