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

Yes, in PHP you can instantiate an object and call a method on the same line. This feature is available starting from PHP 5.4 and is called "object dereferencing" or "method chaining on instantiation".

Syntax

The basic syntax for instantiating and calling a method on the same line is ?

(new ClassName())->methodName()

The parentheses around new ClassName() are required to ensure proper parsing.

Example

Here's a practical example demonstrating object instantiation and method calling on a single line ?

<?php
class Calculator {
    private $value;
    
    public function __construct($initial = 0) {
        $this->value = $initial;
    }
    
    public function multiply($factor) {
        return $this->value * $factor;
    }
    
    public function getValue() {
        return $this->value;
    }
}

// Instantiate and call method on same line
$result = (new Calculator(5))->multiply(3);
echo "Result: " . $result . "<br>";

// Multiple method calls (method chaining)
class ChainExample {
    private $text = "";
    
    public function append($str) {
        $this->text .= $str;
        return $this;
    }
    
    public function getText() {
        return $this->text;
    }
}

$output = (new ChainExample())->append("Hello")->append(" World")->getText();
echo $output;
?>
Result: 15
Hello World

Key Points

When using this syntax, keep these important points in mind ?

  • Parentheses are mandatory(new ClassName()) ensures correct parsing
  • Available from PHP 5.4+ − Earlier versions require separate instantiation
  • Works with method chaining − Multiple methods can be called in sequence
  • Constructor parameters − Pass arguments normally to the constructor

Conclusion

Object instantiation and method calling on the same line makes PHP code more concise and readable. This feature is particularly useful for one-time object usage and method chaining patterns.

Updated on: 2026-03-15T08:29:42+05:30

988 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements