在PHP中调用另一个内的类 [英] Calling a class inside another one in PHP

查看:109
本文介绍了在PHP中调用另一个内的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望您可以帮助我解决这一问题:我有两个类:数据库和用户.数据库使用PDO(在构造函数内部)连接到数据库,并具有更改表,插入数据等功能.Users类将处理登录以及添加/删除用户.但是,Users类需要连接到数据库.我怎样才能做到这一点?

Hope you can help me with this one: i have two classes: Database and Users. The Database connects to the database using PDO (inside the constructor) and has functions to alter tables, insert data, etc. The Users class will handle login, as well add/remove users. However, the Users class needs to connect to the database. How can i do this?

推荐答案

您可以执行以下几项操作:

There are several things you could do:

$db = new Database();

class Users
{
  public function foo()
  {
    global $db;
    $db->query();
  }
}

设置静态变量

$db = new Database();

class Model
{
  static public $db;
}

Model::$db = $db;

class Users extends Model
{
  public function foo()
  {
    self::$db->query();
  }
}

使用单例

class Database
{
   private static $instance;

   private function __construct()
   {
   }

   public static function instance()
   {
      return self::$instance ? self::$instance : self::$instance = new self();
   }
}

class Users
{
   public function foo()
   {
      Database::instance()->query();
      // or $db = Database::instance(); $db->query();
   }
}

您要避免的一件事是为每个模型或类创建一个新的数据库连接.

The one thing you want to avoid is creating a new database connection per model or class.

这篇关于在PHP中调用另一个内的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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