无法实例化另一个PHP中的类

时间:2018-07-18 20:55:49

标签: php

如何在OM内实例化MySQL_DataMapper类?

这是MySQL_DataMapper.php:

<?php
namespace asc {

    include('../../models/OM.php');

    class MySQL_DataMapper
    {
        [omitted code for simplicity]

        public function fetchAllOMs()
        {
            $query = "REALLY LONG QUERY";
            $result = $this->pdo->query($query);
            $OMs = array();
            while ($row = $result->fetch()){
                $OM = new OM($row['id_organizacao_militar'], $row['nome'], $row['sigla'], $row['forca_armada']);
                array_push($OMs, );
            }
            var_dump($OMs);
        }
    }
}

enter image description here

这是我得到的错误:

Warning: include(../../models/OM.php): failed to open stream: No such file or directory in /home/alekrabbe/PhpstormProjects/stm_asc/controller/database/MySQL_DataMapper.php on line 10

Warning: include(): Failed opening '../../models/OM.php' for inclusion (include_path='.:/usr/share/php') in /home/alekrabbe/PhpstormProjects/stm_asc/controller/database/MySQL_DataMapper.php on line 10

Fatal error: Uncaught Error: Class 'asc\OM' not found in /home/alekrabbe/PhpstormProjects/stm_asc/controller/database/MySQL_DataMapper.php:37 Stack trace: #0 /home/alekrabbe/PhpstormProjects/stm_asc/views/cadastro-militar.php(13): asc\MySQL_DataMapper->fetchAllOMs() #1 {main} thrown in /home/alekrabbe/PhpstormProjects/stm_asc/controller/database/MySQL_DataMapper.php on line 37

我不明白为什么它会失败,因为我只是在另一个php文件上这样做了,并且在那里工作了。谢谢。

编辑1

忘记提及了,但是类OM.php也在asc名称空间中。

这里是:

<?php
namespace asc{
    class OM
    {
        private $id;
        private $nome;
        private $sigla;
        private $forca_armada;

        public function __construct($id, $nome, $sigla, $forca_armada)
        {
            $this->id = $id;
            $this->nome = $nome;
            $this->sigla = $sigla;
            $this->forca_armada = $forca_armada;
        }

        [Gets and Sets]
    }
}

2 个答案:

答案 0 :(得分:3)

您位于名称空间中

std

因此对mean的引用将变成namespace asc { 。通过锚定到根名称空间来解决此问题:

OM

答案 1 :(得分:1)

尝试include __DIR__ . "/../../models/OM.php";并确保路径正确

编辑:更好的方法是使用自动加载程序,如@Alex Howansky在对他的回答的评论中提到的那样,但是在紧要关头,请确保路径正确并使用 DIR