Question

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 (\n only) and the character encoding of the file is UTF8.

The PHP setting "auto_prepend_file" is empty.

Était-ce utile?

La solution 3

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.

Autres conseils

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.

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top