Принимать функцию в качестве параметра в PHP
мне было интересно, можно ли передать функцию в качестве параметра в PHP; я хочу что-то вроде того, когда вы программируете в JS:
object.exampleMethod(function(){
// some stuff to execute
});
Я хочу, чтобы выполнить эту функцию где-то в exampleMethod. Это возможно в PHP?
8 ответов:
это возможно, если вы используете PHP 5.3.0 или выше.
посмотреть Анонимные Функции в руководстве.
в вашем случае, можно определить
exampleMethodтакой:function exampleMethod($anonFunc) { //execute anonymous function $anonFunc(); }
просто, чтобы добавить к другим, вы можете передать имя функции:
function someFunc($a) { echo $a; } function callFunc($name) { $name('funky!'); } callFunc('someFunc');Это будет работать в PHP4.
вы также можете использовать create_function чтобы создать функцию в качестве переменной и передать ее. Хотя, мне нравится ощущение анонимные функции лучше. Иди зомбат.
просто код такой:
function example($anon) { $anon(); } example(function(){ // some codes here });было бы здорово, если бы вы могли изобрести что-то вроде этого (вдохновленный Laravel Illuminate):
Object::method("param_1", function($param){ $param->something(); });
согласно ответу @zombat, лучше сначала проверить анонимные функции:
function exampleMethod($anonFunc) { //execute anonymous function if (is_callable($anonFunc)) { $anonFunc(); } }или проверить тип аргумента начиная с PHP 5.4.0:
function exampleMethod(callable $anonFunc) {}
простой пример использования класса :
class test { public function works($other_parameter, $function_as_parameter) { return $function_as_parameter($other_parameter) ; } } $obj = new test() ; echo $obj->works('working well',function($other_parameter){ return $other_parameter; });
PHP ВЕРСИЯ >= 5.3.0
Пример 1: basic
function test($test_param, $my_function) { return $my_function($test_param); } test("param", function($param) { echo $param; }); //will echo "param"Пример 2: std object
$obj = new stdClass(); $obj->test = function ($test_param, $my_function) { return $my_function($test_param); }; $test = $obj->test; $test("param", function($param) { echo $param; });Пример 3: нестатический вызов класса
class obj{ public function test($test_param, $my_function) { return $my_function($test_param); } } $obj = new obj(); $obj->test("param", function($param) { echo $param; });Пример 4: вызов статического класса
class obj { public static function test($test_param, $my_function) { return $my_function($test_param); } } obj::test("param", function($param) { echo $param; });
протестировано на PHP 5.3
как я вижу здесь, анонимная функция может помочь вам: http://php.net/manual/en/functions.anonymous.php
то, что вам, вероятно, понадобится, и это не сказано, прежде чем это как передать функцию, не оборачивая ее внутри функции, созданной на лету. Как вы увидите позже, вам нужно будет передать имя функции, записанное в строку в качестве параметра, проверить его "вызываемость" и затем вызвать его.
в функция для проверки:
if( is_callable( $string_function_name ) ){ /*perform the call*/ }затем, чтобы вызвать его, используйте этот фрагмент кода (если вам также нужны параметры, поместите их в массив), видимый по адресу:http://php.net/manual/en/function.call-user-func.php
call_user_func_array( "string_holding_the_name_of_your_function", $arrayOfParameters );как это следует (аналогичным, без параметров, способом):
function funToBeCalled(){ print("----------------------i'm here"); } function wrapCaller($fun){ if( is_callable($fun)){ print("called"); call_user_func($fun); }else{ print($fun." not called"); } } wrapCaller("funToBeCalled"); wrapCaller("cannot call me");вот класс, объясняющий, как сделать что-то подобное :
<?php class HolderValuesOrFunctionsAsString{ private $functions = array(); private $vars = array(); function __set($name,$data){ if(is_callable($data)) $this->functions[$name] = $data; else $this->vars[$name] = $data; } function __get($name){ $t = $this->vars[$name]; if(isset($t)) return $t; else{ $t = $this->$functions[$name]; if( isset($t)) return $t; } } function __call($method,$args=null){ $fun = $this->functions[$method]; if(isset($fun)){ call_user_func_array($fun,$args); } else { // error out print("ERROR: Funciton not found: ". $method); } } } ?>и пример использования
<?php /*create a sample function*/ function sayHello($some = "all"){ ?> <br>hello to <?=$some?><br> <?php } $obj = new HolderValuesOrFunctionsAsString; /*do the assignement*/ $obj->justPrintSomething = 'sayHello'; /*note that the given "sayHello" it's a string ! */ /*now call it*/ $obj->justPrintSomething(); /*will print: "hello to all" and a break-line, for html purpose*/ /*if the string assigned is not denoting a defined method , it's treat as a simple value*/ $obj->justPrintSomething = 'thisFunctionJustNotExistsLOL'; echo $obj->justPrintSomething; /*what do you expect to print? just that string*/ /*N.B.: "justPrintSomething" is treated as a variable now! as the __set 's override specify"*/ /*after the assignement, the what is the function's destiny assigned before ? It still works, because it's held on a different array*/ $obj->justPrintSomething("Jack Sparrow"); /*You can use that "variable", ie "justPrintSomething", in both ways !! so you can call "justPrintSomething" passing itself as a parameter*/ $obj->justPrintSomething( $obj->justPrintSomething ); /*prints: "hello to thisFunctionJustNotExistsLOL" and a break-line*/ /*in fact, "justPrintSomething" it's a name used to identify both a value (into the dictionary of values) or a function-name (into the dictionary of functions)*/ ?>
Comments