Home > Article > Backend Development > 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!