0

Following is my folder structure

--project
    |_____classes
             |_____config.php
             |_____classes.php
    |_____project
             |_____index.php
             |_____dashboard.php

According to the folder structure, I have all the database configurations in config.php & I have it extended in classes.php and more classes in it.

Now when I use it in the file in dashboard.php in the project folder I have to do something like this includes("../classes/config.php");

I have read the namespace concept in PHP, I have viewed many videos but I am not able to understand the concept that how to use a namespace instead of the include(''); thing.

Can anyone provide me a demo code or source codes .zip file so that I can understand the concept to implement in the project?

Any helps appreciated. Thanks :)

Akshay Shrivastav
  • 1,115
  • 4
  • 17
  • 43

2 Answers2

4

A namespace is not a replacement for include or require.

You can use an autoloading strategy to load classes as required. PSR-4 is a recommended standard for this, and they have an example implementation

If you're using Composer to manage the packages in your project, you can configure it to autoload your classes

clinton3141
  • 4,751
  • 3
  • 33
  • 46
1

Namespace is just a virtual directory system. To use code from another physical file you have to include it, there is no other work around.

just add this line at the top of your page.

use \YOUR\NAMESPACE\HERE;

and, you are good to use that specified namespace now, but still you have to include it.

To add some automation, you can use spl_autoload_register() function to automatically include you files upon class call.

Ataur Rahman
  • 1,671
  • 14
  • 12
  • please can you provide me a demo code probably i am having a problem understand it still :( – Akshay Shrivastav Feb 11 '17 at 11:40
  • /Classes/config.php `` /Project/index.php `hello(); ?>` To omit the `include` part, you can use autoloader package that is available at composer or make it by yourself if you wanna play with it like me. ;) – Ataur Rahman Feb 11 '17 at 11:53
  • In your above code i still have to use the include '../Classes/config.php'; thing how to remove that thing so that I can include that in classes.php and I then just have to call namespace in the dashboard.php – Akshay Shrivastav Feb 11 '17 at 12:07
  • then how to create a autoloader class can you provide an example or that also as you provided for this i am new to composer :( – Akshay Shrivastav Feb 11 '17 at 12:08
  • 1
    I am not fluent in composer either, so I can't help you with it. you better read this : [Basic Hello World with composer and php](https://www.frobiovox.com/posts/2016/08/16/basic-hello-world-with-composer-and-php.html) – Ataur Rahman Feb 11 '17 at 12:37
  • thanks a lot @Ataur Rahman :) – Akshay Shrivastav Feb 11 '17 at 14:59