Call function on returned Object in PHP

by 3 replies
4
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
#programming #call #function #object #php #returned
  • in PHP 5 yes.
  • 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
  • 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

Next Topics on Trending Feed