Chaining a constructor with an object function call in PHP

前端 未结 3 1232
情书的邮戳
情书的邮戳 2021-01-19 13:05

Does anyone know if the following expression will be possible in the next version(s) of PHP?

(new A())->a();    // Causes a syntax error

相关标签:
3条回答
  • 2021-01-19 13:29

    A new-expression can be used as a function argument. A function call can be used as the left-hand side of the member access operator. Therefore, you just need to define a single function:

    function with($object) { return $object; }
    
    with(new A()) -> a();
    

    No additional efforts required on a per-class basis.

    0 讨论(0)
  • 2021-01-19 13:49

    This is possible as of PHP 5.4+:

    Class member access on instantiation has been added, e.g. (new Foo)->bar().

    0 讨论(0)
  • 2021-01-19 13:52

    The first version does not cause a parse error, it is perfectly valid. The second it is, indeed not possible, but you can easily overcome such a problem with some coding standards.

    If every team member creates, for each defined class, a function with the same name as the class, and a signature similar to the signature of the class constructor, then you won't have the second problem. Example:

    class Foo
    {
        public function __construct($param)
        {}
    
        public function bar()
        {}
    }
    
    /**
     * @return Foo
     */
    function Foo($param)
    {
        return new Foo($param);
    }
    
    Foo()->bar();
    

    Of course, you'll still have problems with library code.

    0 讨论(0)
提交回复
热议问题