In PHP, can you instantiate an object and call a method on the same line?

PHPServer Side ProgrammingProgramming

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

 Live Demo

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)
raja
Published on 06-Apr-2020 07:03:52
Advertisements