What are the PHP namespaces that uses and means, and do they autoload classes?

I am trying to educate myself with the functions of PHP 5.3 / PHP 5.4 OOP.

I tried to code something like this. However, this does not work.

index.php

namespace Website; use Website\Database as Database; class Website extends Database { function __construct() { echo "Test"; } } $website = new Website(); 

./Site/database.php

 namespace Website\Database; class Database { function construct() { echo "Hello from Database"; } } 

I know how to create classes, bind them to each other, etc., but every time I add a namespace to the beginning, everything gets broken.

So, I would like to ask a few elementary things:

Q1 : use ClassName; Does it automatically load / enable a class?

Q2 : which means \ without any action on the left side. (e.g. new \ Database ();)

Q3 : Does \ directory mean in PHP, or is it just how developers view it as?

Q4 : What changes should be made in my script to make it work?

+4
source share
2 answers

In response to your first three questions:

Namespacing! == Startup, namespace is a way to simplify your class structures and allows you to "overload" classes in different namespaces; autoload automatically downloads files when they are needed: they are not the same thing. If you use namespaces, you probably also want to use autoloader.

A "lead" \ is the global scope for the namespace; followed by \ then serve as a namespace delimiter

\ - namespace delimiter; directory delimiters / or \ in files depending on the platform; but / works on all platforms, so it really should be used for all cross-platform development. There is also a constant DIRECTORY_SEPARATOR

+3
source

A1: If you use class that has not yet been loaded, the autoloader will start. But you need to write your own autoloader to make sure classes (namespaced) are loaded.

unverified example:

 function autoloader($className){ $fileName = str_replace('\\', DIRCTORY_SEPARATOR, $className); include __DIR__ . $fileName; } spl_autoload_register(autoloader); 

It is assumed that the bootloader is at the root of the application. And it does not perform error checking, and you might need another directory separator added somewhere.

A2: Master \ means global namespace to indicate that the class name is not in the current namespace.

A3: the namespace does not have to match the directory structure, but most developers will prefer it. It also simplifies startup.

+2
source

All Articles