In PHP why can’t I do:
class C
{
function foo() {}
}
new C()->foo();
but I must do:
$v = new C();
$v->foo();
In all languages I can do that…
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In PHP, you can’t call an arbitrary method on a freshly created object like
new Foo()->someMethod();Sorry, but that’s the way it is.
But you could build a work around like this:
Extend CustomContructor like this:
And instantiate them like this:
I have not tested it but this or something like it should work.
Correction: This will only work in PHP 5.3 and later since late static binding is required.