Function call after class creation

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
aliasxneo
Forum Contributor
Posts: 136
Joined: Thu Aug 31, 2006 12:01 am

Function call after class creation

Post 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();
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Function call after class creation

Post 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;
aliasxneo
Forum Contributor
Posts: 136
Joined: Thu Aug 31, 2006 12:01 am

Re: Function call after class creation

Post 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.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Function call after class creation

Post 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 :)
aliasxneo
Forum Contributor
Posts: 136
Joined: Thu Aug 31, 2006 12:01 am

Re: Function call after class creation

Post 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.
Post Reply