Help with PHP call_user_func and integrate function into Class?

て烟熏妆下的殇ゞ 提交于 2019-12-04 16:46:40

The documentation of call_user_func() contains a link to the callback pseudo-type. In short it is either a function name or an array. The array must either contain two strings (a class name and a function name - callback for static functions) or an object and a string (an object and the method to call on that object - for member functions). Here are the examples from the documentation:

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

One more thing: Your locking could be interrupted between add($lock,... and get(). Using increment() and decrement() would solve that problem.

Not directly an answer, but it's worth noting that you don't actually need to use call_user_func - you can just call a variable function:

function ham($jam) {
    echo $jam;
}

$bar = 'eggs';
$foo = 'ham';

$foo($bar);

This should work fine on instantiated objects too:

$bees->$honey($sting);

And there's more info in the docs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!