How can a function be executed directly upon instantiating an object in PHP without the need for a separate code line like $obj->fn()?

To execute a function directly upon instantiating an object in PHP without the need for a separate code line, you can utilize the constructor method (__construct) in the class. By defining the desired function within the constructor, it will be automatically executed when an object is created. This allows you to perform actions immediately upon object instantiation without the need for an additional method call.

class MyClass {
    public function __construct() {
        $this->myFunction();
    }

    public function myFunction() {
        echo "Function executed upon object instantiation.";
    }
}

$obj = new MyClass(); // Output: Function executed upon object instantiation.