programing

메서드를 array_map 함수로 사용할 수 있습니까?

firstcheck 2022. 12. 27. 21:48
반응형

메서드를 array_map 함수로 사용할 수 있습니까?

나는 다음과 같은 것을 하고 싶다.

클래스 Cls {function fun(function fun) {'스페인의 비'를 돌려주세요.;}}
$ar = 어레이(1,2,3);$cls = 새로운 Cls();print_r(array_map$$fun->fun', $ar);
// ^ 이거 안 돼

단, array_map의 첫 번째 인수는 함수의 이름입니다.$instance->fun을 중심으로 래퍼 기능을 쓰는 것은 피하고 싶은데, 그럴 수 없을 것 같습니다.진짜예요?

네, 다음과 같은 메서드로 콜백을 할 수 있습니다.

array_map(array($instance, 'fun'), $ar)

자세한 내용은 PHP 설명서의 콜백 유형을 참조하십시오.

를 사용할 수도 있습니다.

array_map('Class::method', $array) 

구문을 사용합니다.

실제로 Callback의 정의를 알아야 합니다.다음 코드를 참조해 주세요.

<?php 

// An example callback function
function my_callback_function() {
    echo 'hello world!';
}

// An example callback method
class MyClass {
    static function myCallbackMethod() {
        echo 'Hello World!';
    }
}

$myArray = [1, 2, 3, 4];

// Type 1: Simple callback
array_map('my_callback_function', $myArray); 

// Type 2: Static class method call
array_map(array('MyClass', 'myCallbackMethod'), $myArray); 

// Type 3: Object method call
$obj = new MyClass();
array_map(array($obj, 'myCallbackMethod'), $myArray);

// Type 4: Static class method call (As of PHP 5.2.3)
array_map('MyClass::myCallbackMethod', $myArray);

// Type 5: Relative static class method call (As of PHP 5.3.0)
class A {
    public static function who() {
        echo "A\n";
    }
}

class B extends A {
    public static function who() {
        echo "B\n";
    }
}

array_map(array('B', 'parent::who'), $myArray); // A
?>

송신원: http://php.net/manual/en/language.types.callable.php

그것은 다음과 같이 나에게 효과가 있었다.

<?php
class ExcelAutoFilterController extends Controller
{
    public function transpose($value):array
        {
            return [$value];
        }

        public function generateExcelDropdownDownload($file = 'helloWorld.xlsx')
        {

            $countries = [0 => "Algeria"1 => "Angola"2 => "Benin"3 => "Botswana"4 => "Burkina"5 => "Burundi"6 => "Cameroon"7 => "Cape Verde"8 => "Central African Republic"9 => "Chad"10 => "Comoros"11 => "Congo"12 => "Congo, Democratic Republic of"13 => "Djibouti"14 => "Egypt"15 => "Equatorial Guinea"16 => "Eritrea"17 => "Ethiopia"18 => "Gabon"19 => "Gambia"20 => "Ghana"21 => "Guinea"22 => "Guinea-Bissau"23 => "Ivory Coast"24 => "Kenya"25 => "Lesotho"26 => "Liberia"27 => "Libya"28 => "Madagascar"29 => "Malawi"30 => "Mali"31 => "Mauritania"32 => "Mauritius"];

            $countries = array_map('self::transpose', $countries);
        }
        

언급URL : https://stackoverflow.com/questions/1077491/can-a-method-be-used-as-an-array-map-function

반응형