Question

Je veux faire quelque chose comme ceci:

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

mais le premier argument de array_map est censé être le nom de la fonction. Je veux éviter d'écrire une fonction wrapper autour instance- $> amusant, mais il ne semble pas que cela est possible. Est-ce vrai?

Était-ce utile?

La solution

Oui, vous pouvez avoir callbacks aux méthodes, comme ceci:

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

voir le type de rappel dans le manuel de PHP pour plus d'infos

Autres conseils

Vous pouvez également utiliser

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

.

En fait, vous devez connaître la définition de rappel, s'il vous plaît veuillez vous référer au code suivant:

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

De: http://php.net/manual/en/language .types.callable.php

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top