I have a Problem developing in PHP. First I have to say that I’m not the experienced PHP developer on this Planet.
My Code/Problem is as followed:
In file Controllers\TestController.php:
<?php
namespace My\Test\Controllers;
class TestController
{
public function HelloTest()
{
echo 'Hello!';
}
}
?>
When I want to include this class in another php file like this
File Models\TestModel.php:
<?php
namespace My\Test\Models;
use My\Test\Controllers;
class TestModel
{
public function TestModelFunction()
{
$control = new TestClass();
$control->HelloTest();
}
}
?>
File index.php_
<?php
use My\Test\Models;
$model = new TestModel();
$model->TestModelFunction();
?>
That just won’t work… I’ll always get the following error:
Class ‘TestModel’ not found!
When I now add:
include_once 'Models/TestModel.php' in index.php
AND
include_once '..Controllers/TestController.php' in TestModel.php
then it works…
Folder Structure:
Project
|-Models
| TestModel.php
|-Controllers
| TestController.php
|index.php
But do I really have to specify every Time where the files are?
Yes you will always have to include the files that define your classes.
The namespace is just a way to package your classes together, not a way to automatically include PHP files.
If your are looking for a way to automatically include PHP files when needed, have a look on autoload.