7

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?

4
  • 2
    Does the class.dummy.php file have the namespace my_ns; line in it? Commented Feb 24, 2014 at 16:06
  • Another check would be if $obj_dummy=new \dummy(); works as expected. If it does, your class is in the global namespace. Commented Feb 24, 2014 at 16:12
  • This code should work as is. Commented Feb 24, 2014 at 18:03
  • @deceze I'm afraid you have to repeat the namespace line in all included files... Commented Sep 6, 2019 at 7:44

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

Just askin... If a file is to be included in several namespaces is there a work around? I suspect not and I suspect I should stop using so many includes!
@BeNice - include only once and have use my_ns\dummy; in the other files that you want to use it in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.