class MyClass { private $name; public function __construct($name) { $this->name = $name; echo "Hello, $name!"; } } $reflection = new ReflectionClass('MyClass'); $obj = $reflection->newInstanceWithoutConstructor(); $obj->name = "John"; // Output: nothing is printed
class MyClass { private $id; public function __construct($id) { $this->id = $id; echo "Creating object with id $id\n"; } } $reflection = new ReflectionClass('MyClass'); $obj1 = $reflection->newInstanceWithoutConstructor(); $obj2 = $reflection->newInstanceWithoutConstructor(); $obj1->id = 1; $obj2->id = 2; // Output: "Creating object with id 1" and "Creating object with id 2" are not printed.In this example, we define a class `MyClass` with a constructor that accepts an `id` parameter. We create two instances of the class using reflection and `newInstanceWithoutConstructor()` method. Finally, we set the `id` property of each object to a different value without calling the constructor. No output is generated, as the constructor is not executed. The ReflectionClass class is part of the PHP Reflection library, which is included in PHP by default.