Chaining Methods on Newly Created Objects in PHP
In PHP, chaining methods on newly created objects is possible through various techniques.
PHP 5.4 :
In PHP versions 5.4 and above, you can chain methods directly off the object instantiation using parentheses:
(new Foo())->xyz();
PHP 5.3 and Earlier:
In earlier versions of PHP, you cannot chain methods during object instantiation. However, you can use a workaround by wrapping the instantiation in a static method:
class Foo { public function xyz() { return $this; } static public function instantiate() { return new self(); } } $a = Foo::instantiate()->xyz();
Difference Between Chaining Methods:
Prior to PHP 5.4, when you use new Classname();, you cannot chain methods directly off the instantiation. This limitation is due to PHP 5.3's syntax. Once an object is instantiated, you can freely chain methods.
Choosing the Right Method:
The PHP 5.4 method of chaining methods directly from the instantiation is preferred due to its simplicity and elegance. If you need to support PHP 5.3 or earlier, the static instantiation method is a suitable workaround.
The above is the detailed content of When is Method Chaining on Newly Created Objects Possible in PHP?. For more information, please follow other related articles on the PHP Chinese website!