6

I'm trying to use PHP namespaces for the first time and can't even get a very basic example working with 2 files. Here's my directory setup:

/Framework/
/Framework/index.php
/Framework/Models/TestModel.php

And here's the code behind the two files.

index.php:

    namespace Framework;

    use \Framework\Models\TestModel;

    $model = new TestModel();
    $model->test();

TestModel.php:

    namespace Framework\Models;

    class TestModel
    {
        public function test()
        {
            print("test");
        }
    }

The error is simply that it cannot find the TestModel class:

Fatal error: Class 'Framework\Models\TestModel' not found in C:\xampp\htdocs\Framework\index.php on line 7

I'm running the PHP via a web browser at localhost/Framework/index.php. It must be something really simple I'm not seeing, can anyone point it out for me?

  • 2
    We need to see how you autoload classes... – Sergey Eremin Sep 24 '12 at 22:28
  • 4
    You haven't loaded the file with `TestModel` class `require_once 'Models/TestModel.php';` – zerkms Sep 24 '12 at 22:30
  • 8
    What's the point of namespace if you'll have to use require_once? – Eres Feb 19 '17 at 16:25
  • @EresDev To make PHP much more confusing of a language than it was before. (Seriously, many don't like how namespaces were implemented.) That said, technically it's to keep from overlapping names when a lot of files (or a long changes of includes) are added in. Even if you need them for -some- reason, your particular file may need the functions and classes for only a few for what it does. Usually they're a sign that a codebase has gotten so unweildly that nobody fully knows what's going on anymore, and they're a tool to keep from shooting yourself in the foot. – lilHar Oct 11 '18 at 22:00

2 Answers2

5

The Namespace on the File itself "distinguishes" from other classes and functions, however PHP/Server does not know where the physical file is simply based on a Namespace.

So including the file directly, as people has mentioned, lets PHP know exactly what you mean.

When PHP can't find the file, it will call the function spl_autoload_register() and in that method people will usually put a little function to match namespace to directory structure and then load files according.

Another option is to include Composer in your project and use the PSR-4 autoload

{
    "require": {
    },
    "autoload": {
        "psr-4": {
            "App\\": "app_directoy/",
            "Framework\\": "framework_directory/",
        }
    }
}

When including the composer autoload it will look for everything Framework/* within your framework_directory as you defined.

Trent Ramseyer
  • 141
  • 2
  • 2
0

You should remove 'namespace Framework' and include TestModel.php instead in your index.php - Something like this:

require_once('Models/TestModel.php');

use \Framework\Models\TestModel;

$model = new TestModel();
$model->test();
Robert
  • 5,278
  • 43
  • 65
  • 115
dramen
  • 27
  • 3