duanhuhong5255
2013-02-13 21:19
浏览 98
已采纳

PHP命名空间不起作用 - 怀疑PHP配置问题

OK, so, I've been using auto-loaders for a while, become rather used to MVC, and decided to try to tackle namespaces. Well, this hasn't worked as expected. I have managed to reproduce the error in a very simple way, so the contents of my php file read:

<?php
namespace site\test;

echo 'hello';

The output is not what I expected:

Fatal error: Namespace declaration statement has to be the very first statement in the script in file on line 2

I'm running PHP 5.3.10 on a Synology NAS, using the latest version of DSM (Synology's OS). This makes use of Apache v2.2.22. I can confirm that commenting out the "namespace" line returns the word "hello", with no extra characters before it.

There is no BOM at the beginning of the file. I also have no issues with setting headers such as "Location" which would suggest this as being an issue.

Line endings are Unix ( only) and the character encoding of the file is UTF8.

The PHP setting "auto_prepend_file" is empty.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • drip5880 2013-02-16 22:50
    已采纳

    A re-install of the DSM (Synology OS) actually resolved the issue. Once done, some of the classes obtained from other frameworks had the "BOM" bytes at the beginning of the file, but not all. Simple solution to the BOM issues is to add a "BOM" remover into the auto-loader.

    点赞 打赏 评论
  • duan0504 2013-02-13 21:22

    Do you have ANY whitespace before the namespace? The namespace must occur before any output. This includes HTML to the browser. This also includes a UTF-8 Byte Order Mark (BOM) which can creep in from certain editors.

    Try opening the file in an editor such as vi on Linux and it should show you if there's a BOM at the beginning.

    Check How to fix "Headers already sent" error in PHP for information about other ways that output can start in a file.

    点赞 打赏 评论
  • douhuan1979 2013-02-13 21:23

    This happens when you have a file with a UTF-8 BOM as first character and you should remove all whitespaces before the start tag.

    点赞 打赏 评论

相关推荐 更多相似问题