user1695736
user1695736

Reputation:

PHP namespaces not working

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?

Upvotes: 6

Views: 17445

Answers (3)

Ritik
Ritik

Reputation: 39

for namespace in general it is used when you want to create classes with same name and include in file and avoid fatal error . I think according to question author wants to use namespace so the required solution is

require_once('Models/TestModel.php');

   use \Framework\Models as test;

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

Upvotes: 0

Trent Ramseyer
Trent Ramseyer

Reputation: 141

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.

Upvotes: 5

dramen
dramen

Reputation: 27

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();

Upvotes: 0

Related Questions