radio
radio

Reputation: 113

Where is stored namespaced class?

I have PHP namespaced file

namespace A\B\C
$cls = new foo();

Where is the foo class stored?

OR if exist __autoload() how to control directory mapping to namespace?

Thanks for helping. Im trying to closer understand relation between directories and namespaces. PHP and/or Google doesnt give me any answer.

Upvotes: 0

Views: 98

Answers (1)

Bobot
Bobot

Reputation: 1118

There is not direct relation between directories and namespaces, except if you use an autoloader.

If you want this code to works :

namespace A\B\C;
$cls = new foo();

You must do this :

namespace A\B\C;
class foo {}
$cls = new foo();

Or do this :

foo.php

namespace \A\B\C;

class foo {}

index.php

require 'foo.php';

$cls = new \A\B\C\foo();
// or
namespace A\B\C;
$cls = new foo();

Now if you want to use autoloader, you can use something like this :

function autoload($class)
{
    $class = str_replace('\\', '/', $class);

    require_once __DIR__ . '/' . $class . '.php';
}
spl_autoload_register('autoload');

Put this kind of code in top of your index.php and the get a dir arch like this :

A
+ B
| + C
| | + foo.php

Then you just have to do :

$cls = new \A\B\C\foo();

or even :

use \A\B\C\foo;
$cls = new foo();

But anyway, YOU MUST READ MANUAL : Link here

Upvotes: 1

Related Questions