Skip to content
Advertisement

PHP error while (1) Importing a non-compound namespace or (2) Importing any namespace to instantiate a class

An example of a non-compound PHP namespace:

JavaScript

An example of a compound PHP namespace:

JavaScript

If I try to import a non-compound PHP namespace, I get the following error:

Warning: The use statement with non-compound name ‘Html’ has no effect in /home/public_html/Samples/PHP/Namespaces/ImportNamespace1.php on line 34

Next, I tried using a compound PHP namespace. Now the above error (while trying to use the namespace) disappears, but when I try to instantiate a class in the imported namespace, I get the error:

Fatal error: Uncaught Error: Class ‘Table’ not found in /home/public_html/Samples/PHP/Namespaces/ImportNamespace1.php:38

I find that what works is a combination of the following:

  1. Use a compound namespace
  2. Import the class and not the namespace Then, I can instantiate the class without any error along the way.

This is in contrast to what the manual says.

Please note I am using Lightspeed PHP version 7.3.

Here’s the code that works:

Namespace definition: must be compound (in File Namespace1.php):

JavaScript

Import and use the class (rather than the namespace) (File ImportNamespace1.php):

JavaScript

I’d like to ask: Has anyone actually used a non-compound namespace and then imported the namespace (rather than the class) to instantiate a class? Kindly provide actual code.

Advertisement

Answer

If I understand you correctly, I think this is what you are looking for?

JavaScript

I would personally never write code like this, nor did I know that you can alias a namespace, but it appears to work.

Demo: https://3v4l.org/79Dmg

Edit

Here’s a version with two files and without bracketed namespaces

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement