
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
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)
- Related Articles
- Can we call a method on "this" keyword from a constructor in java?
- How can I instantiate a dictionary in JavaScript where all keys map to the same value?
- Call append() method to construct a StringBuffer object in Java
- How do you upcast and downcast the same object in Java?
- How to call the key of an object but return it as a method, not a string in JavaScript?
- Can an object be at rest and in motion at the same time? Give example.
- How do you write a method in Java that can print object in array?
- Download file through an AJAX call in PHP
- In PHP, how can I add an object element to an array?
- Can we call a constructor directly from a method in java?
- How can we call the invokeLater() method in Java?\n
- How to show a bar and line graph on the same plot in Matplotlib?
- How can Tensorflow be used to instantiate an estimator using Python?
- How to do bold and simple text in the same line using the echo in php?
- Can we call methods of the superclass from a static method in java?

Advertisements