繁体   English   中英

php 类中的 Medoo 对象

[英]Medoo object inside a php class

我对如何使用 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分配给类私有变量

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

您可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM