gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:55:50 25 4
gpt4 key购买 nike

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

在自动加载 DBConnect 类时,我无法弄清楚如何使用“use”语句。如果我尝试在加载器函数中的 include 之后添加“use”语句,则会引发错误。所以我不断收到“ fatal error :找不到类‘App\Model\Entity\DbConnect’”。它应该使用“App\Config\DBConnect”。

这是我构建的第一个自动加载器,所以我不确定我哪里出错了。

提前致谢。

Bootstrap

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

自动加载器.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:
}
}

产品.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);
}

数据库连接程序
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();
}
}

最佳答案

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

产品.php:

namespace App\Model\Entity;

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

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

关于PHP如何阻止类继承父类的命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41110116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com