自动加载另一个命名空间中的命名空间时出错

时间:2019-05-24 02:53:03

标签: php composer-php psr-4

尝试从m_newEmployee调用c_index.php时出现以下错误。

我尝试过:

$employee = new \App\model\newEmployee;

但这在m_newEmployee中引起了另一个奇怪的错误。

当我这样做时,功能getEmployees()不能用于创建任何对象。

c_index.php

<?php

namespace app\controller;

use app\model;

require_once "../task/vendor/autoload.php";
  /**
   *
   */
  class c_index
  {

      function loadEmployees()
      {
         $employee = new m_newEmployee;
         echo $employee->getEmployees();
      }


  }


 ?>

m_newEmployee.php

<?php

namespace app\model;
require_once "../task/vendor/autoload.php";
/**
 *
 */
class m_newEmployee
{
    function createTable()
    {
        $database = new m_database;
        $conn = $database->connect();

        // sql to create table
        $sql = "CREATE TABLE IF NOT EXISTS employees (
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        employee VARCHAR(255) NOT NULL,
        created TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )";

        if ($conn->query($sql) === TRUE) {
            //echo "Table MyGuests created successfully";
        } else {
            echo "Error creating table: " . $conn->error;
        }

        $conn->close();
    }


  function createEmployee($employee)
  {

      $this->createTable();
       $sql = "INSERT INTO `employees`( `employee`) VALUES ('$employee')";
       if ($conn->query($sql) === TRUE) {

           $result = true;
           return $result;
       } else {
           echo "Error inserting  " . $conn->error;
       }
  }


  function getEmployees()
  {
      $database = new m_database;
      $conn = $database->connect();

      $sql = "SELECT * FROM `employees`";
      if ($result = $conn->query($sql) === TRUE) {

            //Initialize array variable
            $dbdata = array();

          //Fetch into associative array
            while ( $row = $result->fetch_assoc())  {
            $dbdata[]=$row;
            }

          //Print array in JSON format
           return json_encode($dbdata);
      }

      else {
          echo "Error inserting  " . $conn->error;
      }
    }
  }

composer.json

{
  "autoload":{
    "psr-4":{
      "":"app",
       "App\\":"app"
    }
}

}
  

致命错误:未捕获错误:在C:\ xampp \ htdocs \ task \ app \ controller \ c_index.php:16中找不到类'm_newEmployee':堆栈跟踪:#0 C:\ xampp \ htdocs \ task \ index。 php(14):app \ controller \ c_index->​​ loadEmployees()#1 {main}在第16行的C:\ xampp \ htdocs \ task \ app \ controller \ c_index.php中抛出

1 个答案:

答案 0 :(得分:0)

导入名称空间(use app\model;)并不意味着您可以直接使用该名称空间中的模型。您需要指定名称空间(使用导入时的短名称):

namespace app\controller;
use app\model;
// ...
$employee = new model\m_newEmployee();

或直接导入模型:

namespace app\controller;
use app\model\m_newEmployee;
// ...
$employee = new m_newEmployee();