Home  >  Article  >  Backend Development  >  How Can I Call a Method Immediately After Instantiating an Object in PHP?

How Can I Call a Method Immediately After Instantiating an Object in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 11:49:03766browse

How Can I Call a Method Immediately After Instantiating an Object in PHP?

Instantiating and Accessing Object Methods on the Same Line in PHP

PHP allows for instantiating an object and calling a method on the same line. This feature simplifies code and improves readability, especially for quick operations.

To achieve this behavior, PHP 5.4 introduced a new syntax that enables direct method invocation during object instantiation. This is achieved using the following syntax:

$method_result = (new Obj())->method();

In this example, an object of the Obj class is instantiated and the method() function is called immediately. The result of the method call is stored in the $method_result variable.

Unlike older PHP versions, which require separate steps to instantiate an object and call its methods, this feature provides a more concise and streamlined approach. It reduces the need for intermediate variables and improves code organization.

For instance, instead of writing the following code:

$obj = new Obj();
$method_result = $obj->method();

You can simplify it to:

$method_result = (new Obj())->method();

The above is the detailed content of How Can I Call a Method Immediately After Instantiating an Object in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn