What Up Derek?

  • Archive
  • RSS
  • Ask me anything

answers:

derekreynolds:

marco:

Can PHP do this?

(new Whatever())->function();

It gives me a parse error and makes me do this instead:

$w = new Whatever(); $w->function();

But you can do this perfectly well:

$w->function()->otherFunction();

One hack is to define a function with the same name as the class that returns an instance:

function Whatever() { return new Whatever(); }
/* ... */
Whatever()->function()->otherFunction();

But that’s a hack.

Can’t you just return an instance of itself in the constructor?

// constructor
return $this;

Then when creating a new object

$obj = new Class()->method();

No, that’s the same parse error.

(new Class())->func() and new Class()->func are parsed identically.

What a bust. It made sense. Thanks for the correction!

Source: marco

  • 3 years ago > marco
  • 11
  • Permalink
  • Share
    Tweet

11 Notes/ Hide

  1. lebird liked this
  2. shabdar liked this
  3. jaytee reblogged this from marco and added:
    should be static if you’re wanting to call it this way. :function();
  4. derekreynolds reblogged this from answers and added:
    What a bust. It made sense. Thanks for the correction!
  5. answers reblogged this from derekreynolds and added:
    No, that’s the same parse error. (new Class())->func() and new Class()->func are parsed identically.
  6. 9-bits liked this
  7. marco posted this
← Previous • Next →

About

Pages

  • Resume
  • RSS
  • Random
  • Archive
  • Ask me anything
  • Mobile

Effector Theme by Carlo Franco.

Powered by Tumblr