PHP namespace and include files

namespaces, php

Solution

A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the declare keyword.

Source

Add this to your included file as well.

namespace my_ns;

After that, your code works just fine.

Reference

Problem

I have the following PHP code: ``` <?php namespace my_ns; class dummy { function do_print(){echo "printing...";} } $obj_dummy=new dummy(); $obj_dummy->do_print(); ?> ``` This works all fine, How ever If I put the class in a separate include file (e.g. class.dummy.php), making the code on the page look like below: ``` <?php namespace my_ns; include ("class.dummy.php"); $obj_dummy=new dummy(); $obj_dummy->do_print(); ?> ``` I get the error message: Class 'my_ns\dummy' not found in ... How can by default make sure that (all) include-files are automatically added to a given namespace?

Original source