라이브러리
[PHP] Countable::count - 객체의 요소 수 세기
Countable::count
PHP 7.2 버전부터 Countable 인터페이스가 추가되었습니다. 이 인터페이스는 Countable::count 메서드를 정의합니다. 이 메서드는 객체의 요소 수를 반환합니다.
# Countable 인터페이스
Countable 인터페이스는 다음과 같은 메서드를 정의합니다.
* `count()` 메서드 : 객체의 요소 수를 반환합니다.
# Countable::count 메서드
Countable::count 메서드는 객체의 요소 수를 반환합니다. 이 메서드는 다음과 같은 특징을 가지고 있습니다.
* 객체가 Countable 인터페이스를 구현한 경우에만 호출할 수 있습니다.
* 객체의 요소 수를 반환합니다.
* 객체가 비어 있는 경우 0을 반환합니다.
# 예제
다음 예제는 Countable::count 메서드를 사용하는 방법을 보여줍니다.
#hostingforum.kr
php
class MyCountable implements Countable {
private $items;
public function __construct(array $items) {
$this->items = $items;
}
public function count() {
return count($this->items);
}
}
$myCountable = new MyCountable([1, 2, 3, 4, 5]);
echo $myCountable->count(); // 5
$emptyCountable = new MyCountable([]);
echo $emptyCountable->count(); // 0
# ArrayObject
ArrayObject는 Countable 인터페이스를 구현한 클래스입니다. 따라서 ArrayObject의 인스턴스도 Countable::count 메서드를 호출할 수 있습니다.
#hostingforum.kr
php
$arrayObject = new ArrayObject([1, 2, 3, 4, 5]);
echo $arrayObject->count(); // 5
# SplObjectStorage
SplObjectStorage는 Countable 인터페이스를 구현한 클래스입니다. 따라서 SplObjectStorage의 인스턴스도 Countable::count 메서드를 호출할 수 있습니다.
#hostingforum.kr
php
$storage = new SplObjectStorage();
$storage->attach(new stdClass());
$storage->attach(new stdClass());
echo $storage->count(); // 2
# Array
Array도 Countable 인터페이스를 구현한 클래스입니다. 따라서 Array의 인스턴스도 Countable::count 메서드를 호출할 수 있습니다.
#hostingforum.kr
php
$array = [1, 2, 3, 4, 5];
echo count($array); // 5
결론
Countable::count 메서드는 객체의 요소 수를 반환하는 메서드입니다. 이 메서드는 Countable 인터페이스를 구현한 객체에서 호출할 수 있습니다. ArrayObject, SplObjectStorage, Array도 Countable 인터페이스를 구현한 클래스이므로 Countable::count 메서드를 호출할 수 있습니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.