du67560 2013-09-20 06:43 采纳率: 0%
浏览 36
已采纳

在PHP中使用名称空间

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.

  • 写回答

1条回答 默认 最新

  • dpjhq00684 2013-09-20 06:47
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案