0

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?

2
  • 2
    Read about PHP callables. Commented Feb 21, 2016 at 20:57
  • There's a special callable type. Read more about it. Commented Feb 21, 2016 at 20:57

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh, that's weird. I can just call a string and it will look up the function? Thanks.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.