-4

In PHP can we do this?

function foo($c) {
  $c;

  echo 'done';
}

foo(function() {
  echo 'test'
});

Such that the output will be:

testdone

This was my real problem :

function create_transaction($obj, $func, $errorMsg)
{
  try {
    $obj->transaction('START');

    $func();

    $obj->transaction('COMMIT');
  } catch(Exception $e) {
    $obj->transaction('ROLLBACK');
    throw new exception($errorMsg . ' ---> ' . $e);
  }
}

So i can call this function of create_transaction like this :

create_transaction($obj, function() {
  echo 'test';

  // this should be a database CRUD process
  // to make it simple, i just put echo.
}, 'error');

create_transaction() will inserted the function code between the START and COMMIT.

But this way return an error :

Parse error: syntax error, unexpected T_FUNCTION

This error is in line where i wrote :

create_transaction($obj, function() { // Error here
4
  • 3
    can you please check this link i think it may helps you stackoverflow.com/questions/627775/… Commented May 14, 2016 at 7:32
  • It should work if you execute function c $c() (in the body of foo). Commented May 14, 2016 at 7:33
  • @arjan, the problem is, function c() is dynamic, i want to inject some other code to foo(), so whatever the the process in $c, when it is done, it will echo "done". Commented May 14, 2016 at 9:17
  • @dinesh I'm sorry, i didn't get what you're trying to say. in the page you give me, it written this : "call_user_func('barber', "mushroom");" its the same like this : "barber('mushroom')" right?, why use call_user_func() if you can call the function directly. and what it has to do with my question ?, im sorry, i fail to grasp your point. Commented May 14, 2016 at 9:22

2 Answers 2

0

What you are doing is calling an 'anonymous function'. You are passing the anonymous (which is anonymous because it's unnamed) to another function that invokes it. However, you're not actually invoking it! Specifically because you have encoded $c; rather than $c().

This works as expected:

<?php

function execute_closure($f) {
  echo "Before executing enclosure.\n";

  $f(); //The parens cause php to execute the function

  echo "After executing enclosure.\n";
}

execute_closure(function() {
  echo "Executing enclosured function.\n";
});

Placing this in a file called callfunction.php and executing it yields:

$ php callfunction.php  
Before executing enclosure. 
Executing enclosured function. 
After executing enclosure.

As a final note: anonymous functions only work in PHP 5.3+.

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

4 Comments

I'm sorry, i didn't get what you're trying to say. in the page you give me, it written this : "call_user_func('increment', $a);" its the same like this : "increment($a)" right?, why use call_user_func() if you can call the function directly.
@MarcelAng I think misunderstood your original question. I've updated my response, but this means this is largely a syntax error on your part.
AHA !, this what i meant, what i've done is similar to your way. but in the line "execute_closure(function() {" it return an error : "Parse error: syntax error, unexpected T_FUNCTION". I'll update my question with actual problem.
Ah nevermind !, i found the problem !. Its my php version, i read in your documentation its php 5.3 above, i used 5.2.
0
        <?php

            function foo($c) {
                // CALL THE CALLABLE HERE INSTEAD
                try{
                    $strVal = $c();
                    if(is_string($strVal)){
                        echo $strVal . 'done';
                    }else{
                        // YOUR FUNCTION IS NOT RETURNING A STRING: CATCH & HANDLE THAT CASE:
                        echo "The passed-in Argument Must return a String value...";
                        return false;
                    }
                }catch(Exception $e){
                    // HANDLE THE EXCEPTION YOUR WAY.
                    echo "The passed-in Argument Must be a Callable Function and should return a String value...";
                }
            }

            foo(function() {
                //RETURN THE VALUE HERE!!!
                return "test";
            });

            // SHOULD ECHO BACK 'testdone' TO THE OUTPUT STREAM...

2 Comments

Are you sure that code works ?, because it return an error : "Parse error: syntax error, unexpected T_FUNCTION".
@MarcelAng Someone down here should be asking you the same Question. if you want to test it yourself, here you go: eval.in/571505

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.