gpt4 book ai didi

PHP 命名空间和文件夹

转载 作者:行者123 更新时间:2023-12-04 16:52:58 24 4
gpt4 key购买 nike

如果我有一个 系统根目录中包含 的文件夹数据库带有 的文件夹数据库.php 包含类的文件

class Database{
static function Connect(){
echo "connect";
}
}

我从 index.php 调用它这是在根目录中。

如何创建命名空间来访问类 Database::Connect();我真的在为命名空间而苦苦挣扎。

我需要把 namespace System\Database在我的 Database.php 文件的顶部还是什么?任何不在 php.net 页面上的好例子?

最佳答案

命名空间(在 PHP 中)实际上只是一种防止项目中类之间命名冲突的方法。它们以名为“Zend_Controller_Action_Helper”之类的类的形式使用了一段时间(在它们被正式支持之前)。
PHP5.3 对“真实”命名空间的引入实际上只是意味着我们现在可以通过“使用”命名空间在我们的代码中使用简短易读的名称。

例如。

文件:system/database.php

namespace MyProject;

class Database {
// ...
}

文件 public/index.php
require_once '../system/database.php';

// here we have to use the fully qualified name of the Database class,
// this is similar to the old unofficial underscore method.
$db = \MyProject\Database::connect();

文件:public/index2.php
require_once '../system/database.php';
use MyProject\Database;

// here we can simply use "Database" because the "use" statement says:
// for this file we are using the "Database" class from the "MyProject" namespace
$db = Database::connect();

命名空间仅根据约定(和自动加载)与目录相关,它们本身不会改变包含和使用类的方式。

关于PHP 命名空间和文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13823713/

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