The class candidateService declared namespace app\services; I import it in another class use app\services\candidateService as candidateService; , but PHP does not see it:

Fatal error: Class 'app \ models \ candidateService' not found in Z: \ home \ test.ru \ www \ index.php on line 8

What could be the problem?

index.php

 use app\services\candidateService as candidateService; $candidateService = new candidateService(); $candidate = $candidateService->getCandidate(1); print_r($candidate); 

candidateService.php

 namespace app\services; use app\managers\dbManager as Database; class candidateService { private $Surname, $Name, $Patronymic, $Mail, $LastContact, $Status, $Vacancies, $Database = null; public function __construct() { $this->Database = new Database(); } public function getCandidate($id) { return $this->Database->Query("SELECT * FROM `candidates` WHERE `id`='$id';"); } } 
  • one
    First, use use app\services\candidateService enough to use app\services\candidateService if you don’t want to use an alias for this class. Secondly, how do you include the class itself? - YuS
  • one
    import of a space does not mean require file with this class. - vitidev
  • Write your own loader, which will correctly connect class files - Maxim Vlasov

1 answer 1

You have no connection of this class itself, hence its inaccessibility.

 define('PATH_TO_MODELS',$_SERVER['DOCUMENT_ROOT'].'/PATH/TO/MODELS/'); include_once PATH_TO_MODELS.'candidateService.php'; use app\services\candidateService; $candidateService = new candidateService(); $candidate = $candidateService->getCandidate(1); print_r($candidate); 

In the code you need to specify the path where you have the model. Ideally, spl_autoload_register () is used for this purpose.

And if all your models are in the models folder of the host root and the class name exactly matches the name of the file with this class, the code will look like this.

 define('MODELS',$_SERVER['DOCUMENT_ROOT'].'/models/'); spl_autoload_register('autoload'); function autoload($class) { $file = MODELS.$class.'.php'; if (is_readable($file)) include_once($file); } use app\services\candidateService; $candidateService = new candidateService(); $candidate = $candidateService->getCandidate(1); print_r($candidate);