views:

62

answers:

2

I would like to know whether there's a way to chain methods on a newly created object in PHP?

Something like:

class Foo {
    public function xyz() { ... return $this; }
}

$my_foo = new Foo()->xyz();

Anyone know of a way to achieve this?

A: 

Yup, that's right. As long as the method returns an object (in your case $this), you can keep calling different methods using :: or ->

EDIT

Example

<?php
class Foo {
    public function xyz() { return $this; }
    public static function createInstance() { return new Foo(); }
}

$my_foo = Foo::createInstance()->xyz();
Tim Cooper
Yes, but it seems to not work with constructors.Any ideas?
aefxx
I would assume`public static function createInstance($params...) { return new Foo($params...); }`
Kristoffer S Hansen
+3  A: 

No, when you're using the

new Classname();

syntax, you can't chain a method call off the instantiation. It's a limitation of PHP's syntax. Once an object is instantiated, you can chain away.

One method I've seen used to get around this is a static instantiation method of some kind.

class Foo
{
    public function xyz()
    {
        echo "Called","\n";
        return $this;
    }

    static public function instantiate()
    {
        return new self();
    }
}


$a = Foo::instantiate()->xyz();

By wrapping the call to new in a static method, you can instantiate a class with method call, and you're then free to chain off that.

Alan Storm
+1 Yes I was going to answer "use a factory method," and that's basically what you're showing.
Bill Karwin
I prefer to leave the OO lingo out of the answer when the questioner doesn't appear to be steeped in CS culture. Better they learn the concept and later identify it by its "proper" name than be scared off by new terms.
Alan Storm