创建一个对象并在另一个对象中使用它


Creating an object and using it in another

我对面向对象编程相当陌生。我制作了这个连接到 mysql 数据库的类,以便从模型中调用。有什么方法可以包含"数据库.class.php"(我的数据库类文件)在 index.php 中,将其设为全局,然后从任何类似的对象访问它

$object = new object;
$object->dofunc();

另一个问题是 dofunc() 需要一个用于参数的数组,我如何使这个数组也是全局的,以便可以从任何地方访问它!

这是我的数据库类

<?php
class Database {
    private $db;
    public function connect($config) {
        if (is_array($config)) {
            extract($config);
            $db = mysqli_connect($host, $username, $password);
            if ($db) {
                echo "balbabla";
                if (mysqli_select_db($db, $database)) {
                }
                else {
                    throw new exception("<br/><strong>Could not connect to $database under $host</strong>");
                }
            }
            else {
                throw new exception("<br/><strong>Could not connect to mySQL database! Please check your details</stromg>");
            }
        }
    }
}
?>

这也是包含数组的文件

<?php
//Configuration for the MVC Framework
$_SETTINGS = array();
//Routing settings!
//Default controller(This controller will be loaded if there is none mentioned in the URI)
$_SETTINGS['default_controller'] = 'User';
//Default method(This will be the default method run if no method is mentioned in the URI)
$_SETTINGS['default_method'] = 'Register';
//Database settings
$DB_SETTINGS['host']     = 'localhost';
$DB_SETTINGS['username'] = 'root';
$DB_SETTINGS['password'] = 'foobar';
$DB_SETTINGS['database'] = 'freelance';
?>

提前致谢

有什么方法可以在index.php中包含"database.class.php"(我的数据库类文件),使其成为全局

你可以,但你不应该。

另一个问题是 dofunc() 需要一个用于参数的数组,我如何使这个数组也是全局的,以便可以从任何地方访问它!

你又不应该。

依赖注入是要走的路。

若要从函数中访问全局变量,请使用 global 关键字。例如,要从 Database::connect() 访问 $DB_SETTINGS,您可以执行以下操作:

public function connect() {
    global $DB_SETTINGS;
    ...

然后可以在该函数中访问该数组。

至于全局可访问的类,它们自动就是这样。定义类使其在任何地方都可用。