如何使用OOP将$ db从另一个.php转换为另一个.php的类? [英] How to use $db from another .php to another .php's class using OOP?

查看:74
本文介绍了如何使用OOP将$ db从另一个.php转换为另一个.php的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是OOP PHP的新手,自从开始进行Web开发以来,我就一直在使用过程API,因此我很难迁移到OOP.

I am new to OOP PHP, and I've been working with procedural API since I've started Web Development so I'm having a hard time migrating to OOP.

所以假设我下面有这四个.php文件和结构.

so let's say I have this four .php file and structures below.

connection.db.php

connection.db.php

<?php
    define("DB_HOST", "127.0.0.1");
    define("DB_USER", "root");
    define("DB_PASS", "");
    define("DB_NAME", "sample_db");

    $db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

    echo (!$db->connect_error) ? NULL : die("<pre>Unable to connect to the MySQL Server -> $db->connect_error</pre>");
?>

sampleclass.class.php

sampleclass.class.php

<?php
    public $db;

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

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

includes.inc.php

includes.inc.php

<?php
    error_reporting(0);
    date_default_timezone_set("Asia/Manila");

    require 'connection.db.php';
    require 'sampleclass.class.php';
?>

index.php

index.php

<?php
    require 'includes.inc.php';

    $todo = new MySQLqueries;
    echo $todo->samplefunction("SELECT `sample_column` FROM `sample_table` WHERE `sample_column` = 'sample_value';");
?>

您可能注意到,也可能没有注意到,我的问题是如何在sampleclass.class.phpsamplefunction中使用connection.db.php中的$db

As you may or may have not noticed, my problem is how to use the $db from connection.db.php in the samplefunction of sampleclass.class.php

您可能会问我,为什么不在sampleclass.class.php中创建一个__construct()方法,而只需移动"$ db = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);"那里 ?.好吧,如果我要这样做,所有其他类都必须在其中声明它自己的constructor$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);吗?

You may ask me, why not create a __construct() method in sampleclass.class.php and just move the "$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);" there ?. well if I'm to do this, all other classes will have to have it's own constructor and $db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); declared there right?

connection.db.php上使用$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);时,我假设我可以通用地重用它.

With $db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); on the connection.db.php I assume that I can reuse it versatile-ly.

您看到我已经在sampleclass.class.php中声明了public $db;,但是我不知道下一步是什么.如果有人可以帮助我,那么我将不胜感激.

You see I've declared a public $db; in sampleclass.class.php but I don't know what's next. If someone can help me dearly, then I would be a lot grateful.

PS:我已经咨询过Google博士.关于此问题,我只获得大量文章或视频教程,展示了如何使用和执行OOP PHP-MySQLi编程,而没有使用类和方法.

PS: I've already consulted Dr. Google Ph.D. regarding this matter, and I only got tons of articles or video tutorials showing how to use and do OOP PHP-MySQLi Programming but without using classes and methods.

推荐答案

最好创建一个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.

这篇关于如何使用OOP将$ db从另一个.php转换为另一个.php的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆