1
votes

Why do I have to provide the leading backslash when providing the path to a class? [\Zend\Validator\EmailAddress() and not just Zend\Validator\EmailAddress()]

$validator = new \Zend\Validator\EmailAddress();

$email = "[email protected]";

if ($validator->isValid($email)) { // email appears to be valid } else { // email is invalid; print the reasons foreach ($validator->getMessages() as $messageId => $message) { echo "Validation failure '$messageId': $message\n"; } }

Thanks!

1
Have you declared a namespace at the top of whatever file you're in?Tim Fountain
yes,use Zend\Validator\EmailAddress; But that needs the \ too. The namespace in my file is namespace Blog\Controller;Pat

1 Answers

1
votes

You said you've declared the namespace of Blog\Controller at the start of the class, with:

namespace Blog\Controller

This tells PHP that by default all classes referenced within that class are within the Blog\Controller namespace. So if you were to then do:

$validator = new Zend\Validator\EmailAddress();

what you are actually doing is:

$validator = new Blog\Controller\Zend\Validator\EmailAddress();

which would give you an error since that class doesn't exist.

If you prefix a class with the backslash, you're telling PHP that that class is not in your declared namespace, but instead is in the global space, which is why it then works.

You also said you've imported the EmailAddress class using use Zend\Validator\EmailAddress. This allows you to reference that class as simply 'EmailAddress'. So you change your code to:

$validator = new EmailAddress();

which is much more concise. This is one of the advantages of namespaces - it allows you to use shorter class names in your code.