Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain method on a newly created object?

People also ask

Can you chain methods in Java?

In Java, method chaining is the chain of methods being called one after another. It is the same as constructor chaining but the only difference is of method and constructor.

Which creates a chain class by calling?

The calling of the constructor can be done in two ways: By using this() keyword: It is used when we want to call the current class constructor within the same class. By using super() keyword: It is used when we want to call the superclass constructor from the base class.


In PHP 5.4+, the parser's been modified so you can do something like this

(new Foo())->xyz();

Wrap the instantiation in parenthesis, and chain away.

Prior to PHP 5.4, when you're using the

new Classname();

syntax, you can't chain a method call off the instantiation. It's a limitation of PHP 5.3'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.


Define a global function like this:

function with($object){ return $object; }

You will then be able to call:

with(new Foo)->xyz();

In PHP 5.4 you can chain off a newly instantiated object:

http://docs.php.net/manual/en/migration54.new-features.php

For older versions of PHP, you can use Alan Storm's solution.


This answer is outdated - therefore want to correct it.

In PHP 5.4.x you can chain a method to a new-call. Let's take this class as example:

<?php class a {
    public function __construct() { echo "Constructed\n"; }
    public function foo() { echo "Foobar'd!\n"; }
}

Now, we can use this: $b = (new a())->foo();

And the output is:

Constructed
Foobar'd!

Further information may be found on the manual: http://www.php.net/manual/en/migration54.new-features.php