DiscoInfiltrator DiscoInfiltrator - 5 months ago 9
PHP Question

How does the PHP 'use' keyword work (in Symfony 2)?

In Symfony 2, all requests are getting routed through

app_dev.php
(or
app.php
).

The first few lines look like:

<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
...


In theory, I get that this just imports the specified namespace (or class) to the current scope. What I don't understand is how PHP maps this to a file. For example, the
Debug
class is located in:

vendor/symfony/symfony/src/Symfony/Component/Debug/Debug.php


How does PHP know to look in
vendor/symfony/symfony/src/
?

I'm probably misunderstanding what is happening, but any clarification would be appreciated.

Answer

Knowing which file a class lives in isn't the job of the language, it's the job of the autoloader.

All the use keyword does is this instance is create an alias:

use Symfony\Component\HttpFoundation\Request;

This is saying in the following script, when I refer to Request I really mean Symfony\Component\HttpFoundation\Request. If I use Request object in some way (by either creating an instance or calling a static method on it) then the autoloader will go and try to load the file that class is defined in if it hasn't been loaded already.

The inner workings of the autoloader, though, is different from project to project. There has been a move to standardize autoloader behavior à la PSR-4, but there's nothing in the language saying that you have to adhere to that standard. You could, for instance, have a scheme where all class files reside in a single directory and your autoloader just loads all classes from there, regardless of what namespace they're in.

That scheme would suffer from the fact that you could only have a single class of every name, but there's nothing stopping you from doing it that way.

To answer your question: "How does it know that "Symfony\Component\Debug\Debug" is a valid namespace?"

It doesn't, because it's not actually going out and trying to load that class at this point. If in any random PHP script you put something like this at the top:

use \Non\Existant\ObjectClass;

But don't ever actually use ObjectClass anywhere, you will get no errors. If you try to say new ObjectClass, though, you will get a class not found error.

Comments