将函数名称作为参数传递给函数

时间:2014-01-05 14:55:45

标签: php

我有这样的功能:

function test($str,$func) {
    $func($str);
    //Something more here
}

如何在那里传递函数名称?我想做test("Hello",strtolower);test("Bye",sometextprocessfunc);

3 个答案:

答案 0 :(得分:5)

与任何其他字符串一样,

test("Hello","strtolower");

请参阅variable functions

答案 1 :(得分:3)

function test($str, $func){
    return call_user_func($func,$str);
} 

像这样使用

$asd = test("ASD","strtolower");

答案 2 :(得分:1)

如果您想了解所有可能性,请查看callable types documentation

回拨类型

示例#1回调函数示例

<?php 

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

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

// Type 1: Simple callback
call_user_func('my_callback_function'); 

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

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

// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');

// 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";
    }
}

call_user_func(array('B', 'parent::who')); // A
?>

示例#2使用Closure的回调示例

<?php
// Our closure
$double = function($a) {
    return $a * 2;
};

// This is our range of numbers
$numbers = range(1, 5);

// Use the closure as a callback here to 
// double the size of each element in our 
// range
$new_numbers = array_map($double, $numbers);

print implode(' ', $new_numbers);
?>

另外,看一看其他人已经告诉过你的variable functions

变量函数

示例#1变量函数示例

<?php
function foo() {
    echo "In foo()<br />\n";
}

function bar($arg = '')
{
    echo "In bar(); argument was '$arg'.<br />\n";
}

// This is a wrapper function around echo
function echoit($string)
{
    echo $string;
}

$func = 'foo';
$func();        // This calls foo()

$func = 'bar';
$func('test');  // This calls bar()

$func = 'echoit';
$func('test');  // This calls echoit()
?>

也可以使用变量函数语法调用对象方法。

示例#2可变方法示例

<?php
class Foo
{
    function Variable()
    {
        $name = 'Bar';
        $this->$name(); // This calls the Bar() method
    }

    function Bar()
    {
        echo "This is Bar";
    }
}

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();  // This calls $foo->Variable()

?>

调用静态方法时,函数调用比静态属性操作符强:

示例#3具有静态属性的可变方法示例

<?php
class Foo
{
    static $variable = 'static property';
    static function Variable()
    {
        echo 'Method Variable called';
    }
}

echo Foo::$variable; // This prints 'static property'. It does need a $variable in this scope.
$variable = "Variable";
Foo::$variable();  // This calls $foo->Variable() reading $variable in this scope.

?>