PHP namespaces not working

℡╲_俬逩灬. 提交于 2020-06-27 13:01:48

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/12573808/php-namespaces-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!