Home  >  Article  >  Backend Development  >  Can you instantiate an object and call a method in one line in PHP?

Can you instantiate an object and call a method in one line in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-08 19:04:02508browse

Can you instantiate an object and call a method in one line in PHP?

Instantiating Objects and Calling Methods in a Single Line in PHP

In PHP, one would typically instantiate an object and then call a method on it using separate lines of code. However, a common question arises: is it possible to combine these steps into a single line?

Question: Can an object be instantiated and a method called in the same line in PHP?

Answer: Yes, this feature became available in PHP 5.4. The syntax for this operation is:

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

This allows you to instantiate an object, represented by Obj(), and immediately access one of its methods, method(), assigning the result to the variable $method_result.

Details:

The introduction of this feature in PHP 5.4 addressed requests for a more concise and convenient way to instantiate objects and access their methods. Prior to PHP 5.4, it was necessary to declare the object and then separately call its method:

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

The new syntax streamlines this process, providing a more efficient and readable approach for PHP developers.

The above is the detailed content of Can you instantiate an object and call a method in one line 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