calling a method of an object at instance creation

前端 未结 5 1042
[愿得一人]
[愿得一人] 2020-12-19 18:08

In PHP why can\'t I do:

class C
{
   function foo() {}
}

new C()->foo();

but I must do:

$v = new C();
$v->foo();
         


        
5条回答
  •  情深已故
    2020-12-19 18:25

    You should not be able to execute code like

    new C()->foo();

    in other languages, at least not as long as that language accurately follows logic. The object is not just created using C(), but with the full new C(). Therefore, you should hypothetically be able to execute that code if you include another pair of parentheses: (new C())->foo();

    (Be warned: I haven't tested the above, I'm just saying it should hypothetically work.)

    Most languages (that I've encountered) deal with this situation the same way. C, C#, Java, Delphi...

提交回复
热议问题