简体   繁体   English

在PHP中包含类中心文件的方法

[英]way to include files central for classes in PHP

my class user tries to access the $db object. 我的类用户尝试访问$ db对象。

The problem is that the class user can't find the $db object after including it in my central file loader.inc.php . 问题在于,类用户将$ db对象包含在我的中央文件loader.inc.php中之后找不到 If I include the connect.php in every function/method, it works, but I want a central way to include all my classes and files. 如果我在每个函数/方法中都包含connect.php ,那么它可以工作,但是我希望采用一种集中方式来包含我的所有类和文件。

user.class.php user.class.php

class user {

        public function login($username, $password) {
            $username = $db->real_escape_string($username);
            $password = hash('sha256', $password);
            $stmt = "SELECT username, activation FROM users WHERE username='$username' AND password='$password';";
            $result = $db->query($stmt);
            $count_row = $result->num_rows;
            if ($count_row ==  1) {
                    $userdata = $result->fetch_array(MYSQLI_ASSOC);
                    if ($userdata['activation'] == 0) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    return false;
                }
        }
}  

connect.php connect.php

require_once 'config.php';
require_once 'loader.inc.php';

$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (mysqli_connect_errno()) {
    print mysqli_connect_errno();
} else {
    $db->query("SET NAMES utf8");
}  

loader.inc.php loader.inc.php

require_once 'connect.php';
require_once 'user.class.php'; 

I know that the include function like it's shown here isn't secure, but I use this script only for testing purposes. 我知道这里显示的include函数并不安全,但是我仅将此脚本用于测试目的。

Sincerely 诚挚

Johannes 约翰内斯

You have a variable scope problem. 您有一个可变范围问题。

    public function login($username, $password) {
        $username = $db->real_escape_string($username);
        ...

$db is not defined in the scope of the login() method. $db未在login()方法的范围内定义。

There are several ways to solve that (like sending the database as a parameter to the method, etc.) but a common one in OOP is using dependency injection: When you instantiate a user object, you send the database object as a parameter to the constructor and set a property on the user object. 有几种方法可以解决此问题(例如,将数据库作为参数发送给方法等),但是OOP中常见的一种方法是使用依赖项注入:实例化用户对象时,将数据库对象作为参数发送给构造函数,并在用户对象上设置属性。 Then you can use it everywhere in that class. 然后,您可以在该课程中的任何地方使用它。

A simple example: 一个简单的例子:

class user {
  private $db;

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

  public function login($username, $password) {
    $username = $this->db->real_escape_string($username);
    ...

There are 2 method for solving this. 有两种解决方法。 One that I recommend and one that I don't. 我推荐的一种,我不推荐的一种。

  1. Use the global keyword. 使用全局关键字。

function login($username, $password) { global $db; $db->query(...); }

  1. Use dependency injection and inject into constructor of class (recommended) 使用依赖项注入并注入到类的构造函数中(推荐)

    class User { 类用户{

     private $db; public function __construct($db) { $this->db = $db; } public function login($username, $password) { $this->db->query(...); } 

    } }

You don't understand the principles of object oriented programming. 您不了解面向对象编程的原理。 The classes are independent parts of code. 这些类是代码的独立部分。 Class (and object) can use variables and methods only defined in that class. 类(和对象)只能使用在该类中定义的变量和方法。 The exceptions are static variables and methods. 例外是静态变量和方法。

<?php

    class User {
        protected $var1;
        protected $var2;
    }

In example above the class has defined only two variables and can use only these two variables. 在上面的示例中,该类仅定义了两个变量,并且只能使用这两个变量。 OK. 好。 So what we can do to use external variables like $db ? 因此,我们可以使用$db这样的外部变量做什么呢?

In PHP, we are using Dependency Injection pattern which looks like: 在PHP中,我们使用的依赖注入模式如下所示:

<?php

    class User {
        private $connection;

        public function __construct($connection) {
            $this->connection = $connection;
        }
    }

    $user = new User($db);
    ...

If you don't want to inject $db variable always when you creating new class, you can create class DB using the Singleton anti-pattern or Laravel-like Proxy pattern . 如果不想在创建新类时总是注入$db变量,则可以使用Singleton反模式或类似Laravel的Proxy模式创建class DB

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

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