문제

나는 다음과 같은 일을하고 싶다 :

class Cls {
  function fun($php) {
    return 'The rain in Spain.';
  }
}

$ar = array(1,2,3);
$instance = new Cls();
print_r(array_map('$instance->fun', $ar));
               // ^ this won't work

그러나 array_map에 대한 첫 번째 주장은 함수의 이름이어야합니다. $ instance-> fun 주위에 래퍼 기능을 쓰지 않기를 원하지만 가능하지는 않습니다. 그게 사실인가요?

도움이 되었습니까?

해결책

예, 다음과 같은 방법에 대한 콜백을 가질 수 있습니다.

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

보다 콜백 유형 자세한 정보는 PHP 매뉴얼에서

다른 팁

당신은 또한 사용할 수 있습니다

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

통사론.

실제로 콜백의 정의를 알아야합니다. 다음 코드를 참조하십시오.

<?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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top