라이브러리
[PHP] DsVector::map - 각 값에 콜백을 적용한 결과를 반환합니다.
PHP 에서 DsVector::map은 DsVector 클래스의 메서드 중 하나로, 전달된 콜백 함수를 각 요소에 적용하여 새로운 DsVector 객체를 반환합니다.
DsVector::map 메서드는 다음과 같은 형태로 사용할 수 있습니다.
#hostingforum.kr
php
DsVector::map($callback, $this)
- `$callback` : 전달된 콜백 함수를 지정합니다. 이 함수는 각 요소에 적용됩니다.
- `$this` : 현재 DsVector 객체를 지정합니다.
예제를 통해 DsVector::map 메서드의 사용 방법을 살펴보겠습니다.
예제 1: 숫자의 제곱 계산
#hostingforum.kr
php
use function Dsvector;
// DsVector 객체 생성
$numbers = vector(1, 2, 3, 4, 5);
// DsVector::map 메서드 사용
$squares = $numbers->map(function ($num) {
return $num ** 2;
});
// 결과 출력
print_r($squares);
위 예제에서는 DsVector::map 메서드를 사용하여 각 요소의 제곱을 계산합니다. 결과는 다음과 같습니다.
#hostingforum.kr
php
DsVector {#1
-storage: array:5 [
0 => 1
1 => 4
2 => 9
3 => 16
4 => 25
]
}
예제 2: 문자열의 길이 계산
#hostingforum.kr
php
use function Dsvector;
// DsVector 객체 생성
$strings = vector('hello', 'world', 'php');
// DsVector::map 메서드 사용
$lengths = $strings->map(function ($str) {
return strlen($str);
});
// 결과 출력
print_r($lengths);
위 예제에서는 DsVector::map 메서드를 사용하여 각 요소의 길이를 계산합니다. 결과는 다음과 같습니다.
#hostingforum.kr
php
DsVector {#1
-storage: array:3 [
0 => 5
1 => 5
2 => 3
]
}
예제 3: 객체의 속성 변경
#hostingforum.kr
php
use function Dsvector;
// DsVector 객체 생성
$objects = vector((object)['name' => 'John', 'age' => 30], (object)['name' => 'Jane', 'age' => 25]);
// DsVector::map 메서드 사용
$updatedObjects = $objects->map(function ($obj) {
$obj->age += 10;
return $obj;
});
// 결과 출력
print_r($updatedObjects);
위 예제에서는 DsVector::map 메서드를 사용하여 각 객체의 속성을 변경합니다. 결과는 다음과 같습니다.
#hostingforum.kr
php
DsVector {#1
-storage: array:2 [
0 => (object)[
'name' => 'John'
'age' => 40
]
1 => (object)[
'name' => 'Jane'
'age' => 35
]
]
}
DsVector::map 메서드는 전달된 콜백 함수를 각 요소에 적용하여 새로운 DsVector 객체를 반환합니다. 이 메서드는 다양한 상황에서 유용하게 사용할 수 있습니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.