class MyClass { private $name; function __construct($name) { $this->name = $name; } function getName() { return $this->name; } } $instance1 = new MyClass("John"); $instance2 = new MyClass("Mary"); echo $instance1->getName(); // Output: John echo $instance2->getName(); // Output: Mary
$className = "MyClass"; $instance = new $className();In this example, we dynamically create an instance of the MyClass class by storing the class name in a variable called $className and passing it to the new keyword. Package/library: This method is built-in to the PHP language and does not require any external package or library.