PHP如何阻止类继承父类的命名空间

时间:2016-12-12 21:43:14

标签: php class namespaces

我正在尝试编写自动加载器功能但遇到问题。当我从Product类中调用我的DBConnect类时,它继承了Product类命名空间。

在自动加载DBConnect类时,我无法弄清楚如何使用“use”语句。如果我尝试在我的loader函数中包含include之后添加“use”语句,则会抛出错误。所以我不断收到“致命错误:Class'App \ Model \ Entity \ DbConnect'未找到”。它应该使用“App \ Config \ DBConnect”。

这是我建造的第一台自动装载机,所以我不确定自己哪里出错了。

提前致谢。

bootstrap.php中

require_once('Autoloader.php');
require_once $_SERVER['DOCUMENT_ROOT'] . '/Config/config.php';
spl_autoload_register('Core\Autoloader::loader');

Autoloader.php

namespace Core;
class Autoloader
{
  public static function loader( $class, $dir = null ) {

    if ( is_null( $dir ) )
        $direct  = array(
        '/Controller',
        '/Model/Entity',
        '/Model/Table',
        '/Config'
        );

    foreach ($direct as $dir){

        $scan = scandir(ROOTPATH . $dir);
        $classname = substr(strrchr($class, "\\"), 1);
        $classfile = $classname . '.php';

        foreach($scan as $file)
        {
            if(file_exists(ROOTPATH . $dir . '/' . $classfile)){
                include ROOTPATH . $dir . '/' . $classfile;
                goto xspot;
            }
        }
    }
    xspot:
  }
}

Product.php

namespace App\Model\Entity;
require_once $_SERVER['DOCUMENT_ROOT'] . '/Config/config.php';
include ROOTPATH . '/Core/bootstrap.php';

class Product
 {
    public function __construct($conntype = 'MYSQLI') {
        $db = new DbConnect();
        $this->conn = $db->connect($conntype);
    }

DBConnect.php

namespace App\Config;
class DbConnect {
    function connect() {
        require_once $_SERVER['DOCUMENT_ROOT'] . '/Config/config.php';   
        $conn = new \mysqli(DB_SERVER_MYSQLI, DB_USERNAME, DB_PASSWORD, DB_NAME, DB_PORT);
          if (mysqli_connect_errno()) {
                echo "Failed to connect to MySQL: " . mysqli_connect_error();
          }
 }

2 个答案:

答案 0 :(得分:1)

首先,从require_once $_SERVER['DOCUMENT_ROOT'] . '/Config/config.php';文件中删除行Product.php,因为它已包含在bootstrap.php中 其次,为DbConnect类添加别名,如下所示:

<强> Product.php:

namespace App\Model\Entity;

include ROOTPATH . '/Core/bootstrap.php';
use App\Config\DbConnect as DbConnect;

...
$db = new DbConnect();
...

答案 1 :(得分:0)

添加

  

Product.php

use App\Config;

或使用:

$db = new App\Config\DbConnect();

因为现在对象创建使用了坏名称空间