How to return an array and get the first element of it in one line in PHP?

后端 未结 4 1774
轮回少年
轮回少年 2021-01-22 16:58

this question is just for fun and maybe learning a PHP shorthand trick (if exists) Let\'s assume that I have this code:

$item = $this->get_item($id);
$item =          


        
4条回答
  •  迷失自我
    2021-01-22 17:42

    Nope, as far as I know, there is no way to do this in PHP.

    What you could do is return an object of a class that has a method getLine(). With that, you could do

    $item = $this->prepare_items(array($item))->getLine(0);
    

    you could - I'm not saying it's necessarily always a good idea, but it's becoming more and more popular, probably influenced by jQuery's elegance - also store the results of get_item in the object, and have it return $this to allow for method chaining like so:

    $item = $this->get_item($id)->prepare_items()->getLine(0);
    

提交回复
热议问题