gpt4 book ai didi

php - php 类中的 Medoo 对象

转载 作者:行者123 更新时间:2023-11-29 15:25:33 26 4
gpt4 key购买 nike

我对如何使用 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");
}
}


?>

最佳答案

通过在 __construct() 中传递 $database 来尝试此操作,然后将 $database 分配给类私有(private)变量

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();

关于php - php 类中的 Medoo 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59113345/

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