How can namespaces affect class instantiation in PHP?
When using namespaces in PHP, the namespace must be correctly specified when instantiating a class to avoid conflicts with other classes of the same name in different namespaces. To instantiate a class within a namespace, you need to include the full namespace path before the class name.
// Using namespaces to avoid conflicts when instantiating classes
namespace MyNamespace;
class MyClass {
public function __construct() {
echo 'Class instantiated!';
}
}
// Instantiating MyClass within the namespace
$instance = new MyNamespace\MyClass();