When to use a variable variable in PHP?

后端 未结 8 1779
-上瘾入骨i
-上瘾入骨i 2021-01-03 03:49

I\'ve been developing in PHP for a while now, and I still have not had a task where I\'ve had to use variable variables. Can anyone give me examples where using them is a go

8条回答
  •  暖寄归人
    2021-01-03 04:18

    I haven't found many uses for variable variables but using variables for methods can be handy, as long as what you're doing is clear. For example in a simple REST service you might do something like this:

    $method = $request->getMethod(); // 'post','get','put','delete'
    try 
    {
        $response = $resource->$method($request->getInput());
    }
    catch (BadMethodException $badMethod)
    {
        $response = $responseFactory->getError($badMethod);
    }
    

    Some would argue you could do this equally well with a switch statement (which you could) but this way lends itself to extensibility (if you decide to add another method type) and maintains the abstraction of applying a method on a resource.

提交回复
热议问题