0

How do I call the doSomethingElse function from within this anonymous function?

If I try $this->doSomethingElse() I get 'Using $this when not in object context ' error

class MyController extends AppController {

    public function doSomethingElse()
    {
        //do something
    }


    public function doSomething()
    {
        $this->Crud->on('afterSave', function(CakeEvent $event) {
            if ($event->subject->success) {

                    //how do I call 'doSomethingElse' from here

            }
        }); 
    }
}
3
  • This is not valid code, it's unclear what you're asking exactly. Commented Jun 5, 2014 at 14:38
  • sorry, copied code incorrectly Commented Jun 5, 2014 at 14:44
  • What version of PHP are you using? Commented Jun 5, 2014 at 14:47

1 Answer 1

3

make a reference to your MyController outside your anonymous function and use this like

class MyController extends AppController {

    public function doSomethingElse()
    {
        //do something
    }


    public function doSomething()
    {
        $reference = $this;

        $this->Crud->on('afterSave', function(CakeEvent $event) use ($reference) {
            if ($event->subject->success) {

                    //how do I call 'doSomethingElse' from here
                    $reference->doSomethingElse();

            }
        }); 
    }
}

After PHP5.4 $this can be used in anonymous functions instead pass it as a reference in use (...).

Learn more about anonymous functions in php site

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

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.