'php `use` class in parent folder
I have installed Propel ORM with Composer but I cannot create a new model as the PHP script is not in the same directory as the PHP class.
I have class Test inside Test.php and I want to use it from subfolder/index.php. Note that class Test then uses Base/Test from Base/Test.php, so using require() is not an option here as Base/Test just goes on to use even more classes generated by composer.
Traditionally, I'm supposed to do the following:
<?php
use Test;
?>
but since I have Test in the parent folder, I cannot do that, and obviously
<?php
use ../Test;
?>
doesn't work.
My folder structure:
My Project
|-- Base
| `-- Test.php <-- File referenced by `Test` class
|-- subfolder
| `-- index.php <-- File I want to use `Test` from
`-- Test.php <-- File containing `Test` class
The Actual Code:
subfolder/index.php:
<?php
use \Test;
require __DIR__ . '/../vendor/autoload.php';
$test = new Test();
?>
Test.php:
<?php
use Base\Test as BaseTest;
class Test extends BaseTest
{
}
Solution 1:[1]
Just set all the folder that you want in the composer.json file. Like this:
"autoload": {
"psr-4": {
"App\\": "app/",
"Config\\": "config/"
},
"files": [
"config/config.php"
]
},
Search about the composer.json tho learn more about it. For the example above i chose the namespaces "App" and "Config" for the directories "app/" and "config/" in the root directory of my project AND chose the file "config/config.php" to be running BEFORE any action in my project.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | daniel rodrigues |
