且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用OOP将$ db从另一个.php转换为另一个.php的类?

更新时间:2023-01-07 14:44:42

***创建一个DB类,或者利用已经创建的类来实现您要执行的操作.

You'd be best to create a DB class or harnessing an already created one to achieve what you're trying to do.

通常这样的流程是延迟加载/依赖项注入.将所需的对象传递到类中的位置.

The usual flow for things like this is call Lazy Loading/Dependency Injection. Where you're passing the required objects into the class.

如果您选择此路径,我建议您阅读Dependency Injection,因为它有很多优点和缺点,但是在OOP中是必不可少的.

依赖注入是OOP中的关键原则.我想补充一点 如果您对OOP持认真态度,还应该查看 一般 PSR-4

Dependency injection is a key principle in OOP. I'd like to add that if you are serious about OOP you should also look into autoloaders in general, PSR-4 and Composer.

除了上述提到的方面之外,您***查看> PHPTheRightWay ,其中列出了很多内容,包括依赖注入.

A side not on the above mentioned, you'd be best to look at PHPTheRightWay, they list a lot of stuff, including Dependency Injection.

您最终将创建类似的内容.***遵循以下示例以了解其工作原理:

You'll end up creating something like. It'd be better if you followed this example to understand how it works:

Class DB {

    function __construct($host, $user, $pass, $db) { 
        return $this->connect($host, $user, $pass, $db); 
    }

    function connect($host, $user, $pass, $db) {
        //..connect and all.
    }

    //...the rest of your functions/class...
}

您可以随时构建此结构.或者只是使mysqli对象可访问,允许您调用它.

You can construct this anyway you please. Or just make the mysqli object accessible, allowing you to call it.

现在我们来看看有趣的东西.实际上将其注入您的班级;

Now we get to the fun stuff. Actually injecting it into your class;

Class Foo {

    $private $db;

    // your construct method here will ONLY except a `DB` class instance/object as $db. 
    // Try it with anything else and learn from the errors to understand what I mean.
    function __construct(DB $db){
        $this->db = $db;
    }

}

$db = new DB($host, $user, $pass, $db);
// you can error check it here

$foo = new Foo($db);// inject the $db object.


如果您只想共享资源,则可以利用global,但强烈建议不要这样做.

include('connection.db.php');

class MySQLqueries {
        public function samplefunction($queryString) {
            global $db;
            $sqlQry = mysqli->query($queryString);

            return ($sqlQry) ? "<pre>Query Executed Successfully</pre>" : die("<pre>An error occured -> $db->error</pre>");
        }
}

如果选择此路径,则***将$dbglobal实例分配给内部类变量,例如$this->db.

If you chose this path, you'd be best to assign the global instance of $db to an internal class variable, like $this->db.