0

I am trying to figure out how to use the namespace in php. I have been reading about how to use it and for some reason I can not get it to work. I have two files one which I have stored in Applications/Database/Classes file name is DatabaseConnection.php and the other in the root directory called DB.phpinside the DatabaseConnection.php file I have the following code:

<?php
    function hello()
    {
        echo "hello";
    }
?>

This is the DB.php file contents:

<?php
namespace Applications\Database\Classes;
ini_set('display_errors', true);
hello();
?>

Maybe I am completely missing how to use it properly but if I set a namespace is that the same as using include or require? I might be completely misunderstanding how to use it. I am new to OOP and have never heard of namespaces until I started trying to learn OOP? Can someone point out what I did wrong.

6
  • I know some Trekkies ... they use spacenames nearly in the same way you do ;) Commented Sep 21, 2013 at 19:31
  • I never got into star trek Commented Sep 21, 2013 at 19:34
  • 2
    namespaces dont automatically require files. You could however use an autoloader Commented Sep 21, 2013 at 19:34
  • @Yamaha32088 You did not get it! Commented Sep 21, 2013 at 19:35
  • I know I didn't get it haha Commented Sep 21, 2013 at 19:36

2 Answers 2

1

Namespaces are for organizing your code in so that you can divide components up and help with the readability. For example if I have a class Pittbull and another Dashund I can place them into a namespace like so for organization:

Animals.Dogs.Pittbull
Animals.Dogs.Dashund

This also helps with potential collisions like the below:

Animals.Dogs.Misc
Animals.Cats.Misc

The Misc class exists twice in this instance, but instead of there being a conflict of which Misc to use, you can use the same class name for both classes (and have different properties and methods inside of them) and not have a conflict of which one you want to use.

The require keyword is a completely different concept and is used to load actual files into the executing script.

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

Comments

0

Instruction how to use autoloading in PHP (PSR-0):
https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md

Comments

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.