How can a second class in PHP have a reference to an interface and instantiate an object of the class that implements the interface?
To have a second class in PHP reference an interface and instantiate an object of a class that implements the interface, you can first create the interface with the required methods. Then, have a class implement the interface and define the methods. Finally, in the second class, reference the interface, instantiate an object of the implementing class, and call the methods defined in the interface.
<?php
// Define the interface
interface MyInterface {
public function myMethod();
}
// Implement the interface in a class
class MyClass implements MyInterface {
public function myMethod() {
echo "Method implementation in MyClass";
}
}
// Reference the interface and instantiate the implementing class in a second class
class SecondClass {
public function __construct() {
$object = new MyClass();
$object->myMethod();
}
}
// Instantiate the SecondClass to see the output
new SecondClass();
?>