简体   繁体   中英

Load class from vendor folder inside autoloaded class from a folder outside vendor

I have a php application with a folder structure like this

-/app
-/vendor
-index.php

My "vendor/autoload.php" file is included in "index.php" file. When I call a class from vendor for example upload() in "index.php" file it loads without a problem. However if I call the same class in a method from a class inside "app" folder it shows class not found error.

Classes inside "app" folder are autoloaded like this

"autoload": {
    "psr-4":{
        "App\\": "app/"
    }
},
"require": {
    "verot/class.upload.php": "dev-master"
}

How can I call classes from vendor folder inside autoloaded classes in app folder?

Edit:

Classes from app folder are called in "index.php" like this

include("vendor/autoload.php");
$get_class = 'User';
require_once('app/'.$get_class.'.php');
$get_class = 'App\\'.str_replace('/', '\\', $class_name);
if(method_exists($get_class , 'uploadImage')) {     
 $class = new $get_class();
 $class->{ 'uploadImage' }();
}

Here is the upload() class being called in User class

namespace App\User;

class User{
 public function uploadImage() 
 {
   $file = 'user.jpg';
   $handle = new upload($file);
 }
}

Here is the error message

Class 'App\upload' not found in app/User.php:20

This is a namespace issue. You need to either add:

use upload;

under the namespace declaration in you App\\User -file to import the upload-class or you need to use the full namespace to the upload class when using it:

$handle = new \upload($file); 

You can read more about it in the manual

Note: In the posted code, $file is undefined when you're trying to use it in uploadImage() -function.

Note 2: If you've included vendor/autoload.php in the top of your index.php (which you should), there's no need to include the classes manually in PHP. Composers autoloader will handle that automatically. Just to: $user = new App\\User .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM