php variable function

Published 2 months ago by Snapey

I have this ugly bit of code but can't seem to find the right syntax to simplify it

    $r=$request->response;
    $this->$r($task);

$request->response is a string corresponding to one of three buttons on a form. The buttons have values of 'approve', 'query' and 'refuse'

in the snippet I am trying to call a function that has the name specified in the request. So, if the user presses 'approve' then $this->approve() is called

I tried $this->$request->response($task); but the syntax is not right.

it works as I have it now but it's annoying me everytime I see that $r variable

and, yes, my form request validates that response can only be one of the three method names.

Best Answer (As Selected By Snapey)
bunnypro

how about

$this->{$request->response}($task);

or

call_user_func([$this, $request->response], $task);
jimmck

@Snapey Calling a Closure? That is the correct method for doing it. Its a PHP quirk have not researched in 7.x yet.

   public function __construct(\Closure $sorter = null, $addAfter = true)
    {
        $this->tree = array();
        $this->size = 0;
        $this->order = 1;
        /** @type \Closure $sorter */
        $this->sorter = $sorter;
        $this->addAfter = $addAfter;
        $this->window = 5;
        $this->delimeter = "|";
        $this->keys = null;
    }
Snapey
Snapey
2 months ago (577,135 XP)

@jimmck no not a closure.

Part of the issue is that I don't know the correct terminology. It's sort of polymorphic in that the data determines the function name to be called.

It works fine on two lines and a temporary variable but not with the extra arrow in there

Snapey
Snapey
2 months ago (577,135 XP)

I'll call that a blank then..

bunnypro

how about

$this->{$request->response}($task);

or

call_user_func([$this, $request->response], $task);
Snapey
Snapey
2 months ago (577,135 XP)

YES! $this->{$request->response}($task);

Thanks

jimmck

@Snapey Are you using withCallback? What is does the code look like? This looks just like a Closure. Did you define the function? Where?

Snapey
Snapey
2 months ago (577,135 XP)

Yes, I have three functions defined in the controller. The user submits the form by pressing one of three buttons.

I want the value returned by the button to determine the function to call rather than testing for each case with a select.

eg;

    public function authorise_photo_response(AdminApprovePhoto $request, Task $task)
    {

        $this->{$request->response}($task);

        return redirect(route('admin.tasks'));
    }


    public function queryPhoto($task)
    {
        //  query workflow
    }

    public function declinePhoto($task)
    {
        // decline workflow
    }

    public function approvePhoto($task)
    {
        // approve workflow
    }

So no, callback not required.

Sign In or create a forum account to participate in this discussion.