Reputation: 10101
I see some example code such as
$log = new Monolog\Logger('name');
Why not always use the fully qualified class name instead?
$log = new \Monolog\Logger('name');
So you don't need to worry if this file is being used in whatever namespace, right?
Upvotes: 3
Views: 980
Reputation: 3326
You would use a fully qualified namespace if you are referencing a class from a separate namespace. For example:
<?php
namespace Foo\Bar;
class ClassName
{
function __construct()
{
$this->foobar = new Monolog\Logger;
}
}
In this situation, $this->foobar
would be resolved to an instance of Foo\Bar\Monolog\Logger
.
If Monolog is a completely different package from Foo\Bar
, we don't want this to happen, so we use the fully qualififed namespace.
If you used the fully-qualified namespace of \Monolog\Logger
, $this->foobar
would be an instance of Monolog\Logger
.
Use the fully-qualified namespaces if you are using classes from a separate package/namespace in a namespace of your own. Use just the qualified namespace if you are using classes within the same namespace.
Upvotes: 2