Page 1 of 1

Function call after class creation

Posted: Sat Apr 26, 2008 11:26 am
by aliasxneo

Code: Select all

<?php
 
class Test
{
    function tester()
    {
        print "test";
    }
}
 
$test = new Test()->tester();
 
?>
I was actually surprised to see that code not working. Does anyone know if I am doing something wrong and if so is there a way I can get this same effect or is it simply not possible?

The reason why I'm even trying this is because in my application I have a class that loads some external files and has a function called getContent() that returns the loaded content and I prefer to just do:

Code: Select all

$content = new Loader("blah.html")->getContent();
Rather than:

Code: Select all

$loader = new Loader("blah.html");
$content = $loader->getContent();

Re: Function call after class creation

Posted: Sat Apr 26, 2008 11:30 am
by John Cartwright
You cannot do chaining with the constructor, since it technically does not return anything. Use a static method to load the instance and return the instance, i.e. return $this;

Re: Function call after class creation

Posted: Sat Apr 26, 2008 11:31 am
by aliasxneo
Jcart wrote:You cannot do chaining with the constructor, since it technically does not return anything. Use a static method to load the instance and return the instance, i.e. return $this;
Ah that makes sense. I'll try the static then, thanks.

Re: Function call after class creation

Posted: Sat Apr 26, 2008 9:23 pm
by Chris Corbyn
I think PHP 5.3 (or 6) is going to allow such constructs as "new Foo()->bar()";. Don't know why I'm thinking that though... I just seem to remember reading something on the internals list. It's easily worked around anyway and usually the workaround is a better approach :)

Re: Function call after class creation

Posted: Sat Apr 26, 2008 9:27 pm
by aliasxneo
Chris Corbyn wrote:I think PHP 5.3 (or 6) is going to allow such constructs as "new Foo()->bar()";. Don't know why I'm thinking that though... I just seem to remember reading something on the internals list. It's easily worked around anyway and usually the workaround is a better approach :)
Sweet :) That would be really helpful for what I'm trying to do. Thanks for the tip.