Call function on returned Object in PHP

3 replies
Is it possible to do the following?

$result = function1()->function2()->function3();

It's very handy to write code like this, easier to read and shorter too!

The only alternative I see is this:
$first = function1();
$second = $first->function2();
$result = $second->function3();

This is assuming function1 returns an object containing function2 and function2 returns an object containing function3.

So the question remains.. is this possible:
$result = function1()->function2()->function3();

Thanks!
Sean
#call #function #object #php #returned
  • Profile picture of the author Mark Brian
    in PHP 5 yes.
    Signature

    {{ DiscussionBoard.errors[788828].message }}
  • Profile picture of the author Sean Kelly
    Example:

    In Java this is possible:

    int count = new Family().getEldestChild().getNumberOfToes();

    In PHP I would assume it would be something like this:

    $count = new Family()->getEldestChild()->getNumberOfToes();

    but I'm having no luck with it. Google searches didn't help either.

    Any ideas if this is possible?

    Sean
    Signature
    http://javadocs.com - Javadocs
    {{ DiscussionBoard.errors[788832].message }}
  • Profile picture of the author Sean Kelly
    Thanks Mark, yes you're right, I needed to upgrade my version of PHP, I was using an old version of WAMP. It's working now.

    Beautiful!

    Sean
    Signature
    http://javadocs.com - Javadocs
    {{ DiscussionBoard.errors[788932].message }}

Trending Topics