Search code examples
phpsymfony1

Using call_user_func() with objects


The following two statements should be identical, yet the commented out statement does not work. Can anyone explain ?

$peer = GeneralToolkit::getPeerModel($model);
//return call_user_func(get_class($peer).'::retrieveByPK',array($comment->getItemId()));
return $peer->retrieveByPK($comment->getItemId());

PS: I am using PHP 5.2.11


Solution

  • The two calls are not the same. You are calling:

    return GeneralToolkit::retrieveByPK(array($comment->getItemId());
    

    So of course you get a different answer. This is the correct code:

    return call_user_func(array($peer, 'retrieveByPK'), $comment->getItemId());
    

    Unless 'retrieveByPK' is static, but in that case you should use one of these calls (these all do the same thing):

    return call_user_func(
        get_class($peer) . '::retrieveByPK', 
        $comment->getItemId());
    
    return call_user_func(
        array(get_class($peer), 'retrieveByPK'), 
        $comment->getItemId());
    
    return call_user_func_array(
        get_class($peer) . '::retrieveByPK', 
        array($comment->getItemId()));
    
    return call_user_func_array(
        array(get_class($peer), 'retrieveByPK'), 
        array($comment->getItemId()));
    

    So in that case your error was in using array() while calling call_user_func() instead of call_user_func_array().

    Explanation:

    Classes have two main types of functions: static and non-static. In normal code, static functions are called using ClassName::functionName(). For non-static functions you need first to create an object using $objectInstance = new ClassName(), then call the function using $objectInstance->functionName().

    When using callbacks you also make a distinction between static and non-static functions. Static functions are stored as either a string "ClassName::functionName" or an array containing two strings array("ClassName", "FunctionName").

    A callback on a non-static function is always an array containing the object to call and the function name as a string: array($objectInstance, "functionName).

    See the PHP Callback documentation for more details.