Question

I am working on the AWS documentation which uses Guzzle framework. I have to deal with namespaces here and I am not able to get it working. I went through the docs and examples and understood that we can have packages for projects using namespaces.

I went ahead and tried a simple example, but unsuccessful. Here's the example: this is the index.php:

     use My\Full\Classname as Another;  //Also tried use My\Full\Classname
     $obj = new Another;                //with  $obj = new Classname;    
     echo $obj->add();

I have Classname.php in the directory structure like this My->Full->Classname.php:

     <?php
        class Classname{
        public static function add(){
                return 2+2;
            }
         }
     ?>

I am trying to call the function in index.php but getting error:

Fatal error: Class 'Another' not found in C:\wamp\www\guzzleEx\index.php on line 19

which is the line where I instantiate the Classname object $obj = new Another;

What is the mistake i am making? Is there any INI that needs to be updated or any other config issue? How can I make the code working? If you use the normal include for Classname.php it works fine.

Was it helpful?

Solution

Namespaces need to be explicitly declared, they do not come from a certain directory structure.

So if you do not have a line that reads namespace My\Full; in front of your class Classname, then your class is not in any namespace, but in the root namespace.

Thus you cannot use it as \My\Full\Classname, but \Classname or even Classname directly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top