0

我对如何使用 meddo 配置类感到困惑

$database = new Medoo([
    'database_type' => 'mysql',
    'database_name' => 'name',
    'server' => 'localhost',
    'username' => 'your_username',
    'password' => 'your_password',
]);

在另一个班级内

class Blog {
    public function getBlogs(){
       return $database->select('post', "title");
    }
}

现在我正在使用全局变量来解决它们是我可以使用的任何直接方式。

我不想这样使用它

<?php
include 'classes/config.php';

class blog{


function A(){
    global $database;
    return $database->select('post', "title");
    }
}


function B(){
    global $database;
    return $database->select('post', "title");
    }
}


function C(){
    global $database;
    return $database->select('post', "title");
    }
}


?>
4

2 回答 2

0

通过传入然后分配给类私有变量来$database试试这个__construct()$database

include 'config.php';
class blog{
    private $database = null;

    function __construct($db)
    {
        $this->database = $db;
    }

    function A(){
        $this->database->select('post', "title");
    }
}

$obj = new blog($database);
$obj->A();
于 2019-11-30T05:52:56.347 回答
0

您可以使用use关键字来引用函数的数据库对象。

https://www.php.net/manual/en/functions.anonymous.php

$database = new Medoo();

class Blog {

    public get() use ($database) {
        return $database->select('post', "title");
    }
}

或者使用官方推荐的单例模式。

https://medoo.in/api/collaboration

于 2019-12-05T21:12:28.117 回答