Viewed   86 times

I have an Exception class:

namespace abc;

class AbcException extends Exception {
// blah blah
}

It produces this error:

Class 'abcException' not found ...

Questions:

  1. What can I do to make this work ?

  2. Useful documents are appreciated.

Thanks for reading my question

 Answers

5

What can I do to make this work ?

Use a leading backslash to indicate the global namespace:

namespace abc;

class AbcException extends Exception {
// blah blah
}

Useful documents are appreciated.

There's an entire page devoted to this in the PHP manual!

Sunday, December 11, 2022
1

Use:

$_SERVER['DOCUMENT_ROOT'];
Monday, September 5, 2022
 
dogbert
 
5

To clear up any confusion regarding different syntax use, namespaces support only two syntaxes, either bracketed or simple-combination both will work. I suggest if you use one over the other, be consistent.

<?php
namespace mystuffnested {  // <- bracketed syntax
 class foo {}
}
?>

It creates a class foo inside of the nested namespace with bracketed syntax ({}), it is equivalent to

<?php
namespace mystuff {  // bracketed syntax but with a nested look
  namespace nested {
     class foo {}
  }
}
?>

You can also use nested namespaces with simple-combination syntax (;)

<?php
namespace mine;
use ultralongnsname;  // <- simple-combination syntax

$a = nameCONSTANT;
namefunc();
?>

PHP: FAQ: things you need to know about namespaces

Wednesday, August 3, 2022
 
5

Relative namespaces aren't supported. There's a request for it though: https://bugs.php.net/bug.php?id=52504

If you import your classes at the top of the file it shouldn't be that big of a deal.

namespace InoriTestSubTest;
use InoriTestMainTest;

class SubTest extends MainTest { }
Sunday, November 13, 2022
 
www139
 
5

The use operator is for giving aliases to names of classes, interfaces or other namespaces. Most use statements refer to a namespace or class that you'd like to shorten:

use MyFullNamespace;

is equivalent to:

use MyFullNamespace as Namespace;
// NamespaceFoo is now shorthand for MyFullNamespaceFoo

If the use operator is used with a class or interface name, it has the following uses:

// after this, "new DifferentName();" would instantiate a MyFullClassname
use MyFullClassname as DifferentName;

// global class - making "new ArrayObject()" and "new ArrayObject()" equivalent
use ArrayObject;

The use operator is not to be confused with autoloading. A class is autoloaded (negating the need for include) by registering an autoloader (e.g. with spl_autoload_register). You might want to read PSR-4 to see a suitable autoloader implementation.

Friday, September 16, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :