Carcigenicate
Carcigenicate

Reputation: 45826

PHP - Pass named function to another function

I have a function collectRows that accepts a sqli_result object, and returns the query results as a array of rows:

function collectRows($result) {
    ...
}

and have another function that accepts a function to decide what to do with the query results before returning them:

function execQuery($query, $resultsF=null) {
    ...    
}

I want to use execQuery like so:

execQuery("SELECT * FROM...", collectRows);

But I get complaints that it can't find the constant "collectRows".

Obviously, I could do something like:

execQuery("SELECT * FROM...", function($result) {
    return collectRows($result);
});

But it would be nice to be able to write it a more succinctly.

Is there a way to pass a named function without wrapping it in an anonymous function?

Upvotes: 0

Views: 60

Answers (2)

Jim Driscoll
Jim Driscoll

Reputation: 904

Quite simply, you only have to pass the name as a string. PHP doesn't care, it'll deal with it anyway.

Upvotes: 1

u_mulder
u_mulder

Reputation: 54796

Function name instead of function itself should be passed to a function:

function execQuery($query, $functionName=null) {
    if (is_callable($functionName)) {
        $functionName();
    }
}

And call it:

execQuery("SELECT * FROM...", 'collectRows');

More info about callable type.

Upvotes: 2

Related Questions