duanguoping2016 2015-01-07 14:28
浏览 83
已采纳

PHP无法使用命名空间创建类的实例

I've got the following problem:

This is my super basic class:

class A
{
    function foo()
    {
        echo "bar";
    }
}

Now in front of the class declaration I use the following code:

$a = new A();
$a->foo();

When I open the php file in the browser, the output is "bar". Fine!

Now I want to do the same thing in another file.

directly in the first place I declare the following namespace:

namespace model\dbAction;

This is the path where my file with the class above is located.

So in another php file I do the following:

$a = new \model\dbAction\A();
$a->foo();

But I don't get any output and other code after that won't run so it looks like it breaks directly after the instancing of the class.

Any ideas why instancing the class in another file is not working?

Thanks!

Full code first php file:

<?php
namespace model\dbAction;
class A
{
    function foo()
    {
        echo "bar";
    }
}

Full code of the second file (which I call in the browser):

$a = new \model\dbAction\A();
$a->foo();
  • 写回答

1条回答 默认 最新

  • doudiza9154 2015-01-07 15:37
    关注

    You still need to include the file -- providing the namespace itself will not include the file for you... unless you're using an autoloader. See: How do I use PHP namespaces with autoload?

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

报告相同问题?

悬赏问题

  • ¥15 如何让子窗口鼠标滚动独立,不要传递消息给主窗口
  • ¥15 如何能达到用ping0.cc检测成这样?如图
  • ¥15 关于#DMA固件#的问题,请各位专家解答!
  • ¥15 matlab生成的x1图不趋于稳定,之后的图像是稳定的水平线
  • ¥15 请问华为OD岗位的内部职业发展通道都有哪些,以及各个级别晋升的要求
  • ¥20 微信小程序 canvas 问题
  • ¥15 系统 24h2 专业工作站版,浏览文件夹的图库,视频,图片之类的怎样删除?
  • ¥15 怎么把512还原为520格式
  • ¥15 MATLAB的动态模态分解出现错误,以CFX非定常模拟结果为快照
  • ¥15 求高通平台Softsim调试经验