- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
In PHP, can you instantiate an object and call a method on the same line?
Yes, an object can be instantiated and a method can be called on a single line using PHP. This feature has come into effect beginning from PHP version 5.4.
An object can be instantiated by accessing the class member of the class. This can be seen in the below snippet −
(new my_var)-> my_instance()
Code explanation − Here, my_instance is the method and my_var is the object that needs to be instantiated.
Example
class Test_class { public function __construct($param) { $this->_var = $param; } public function my_method() { return $this->_var * 2; } protected $_var; } function Test_class($param) { return new Test_class($param); } $a = Test_class(10)->my_method(); var_dump($a);
Output
This will produce the following output −
int(20)
Advertisements