1

我对 PHP OO 概念比较陌生。我一直在搞乱以下,

<?php

require('class_database.php');
require('class_session.php');

class something {  

  $database = NULL;
  $session = NULL;

  function __construct() {
    $this->database = new database();
    $this->session = new session();
  }

  function login() {
    $this->session->doLogin();
  }
}
?>

in another script

$something = new something();
$something->login();

在这个例子中,$database有一个构造函数,它创建一个包含 MySQLi 连接的受保护变量。它还有一个名为query().

如果$session需要运行$database->query,我该怎么做?创建一个新的数据库类会非常浪费,但我似乎无法$database$session.

我是否为自己制造了本应避免的大麻烦?我希望会话提供登录验证,这需要访问数据库以检查凭据。

谢谢你的帮助

4

2 回答 2

3

有关此主题的更多信息,请参阅http://en.wikipedia.org/wiki/Dependency_Injectionhttp://martinfowler.com/articles/injection.html

<?php
class something {  
  require('class_database.php');
  require('class_session.php');

  $database = new database();
  // dependency injection either here in constructor or in the function that needs it below
  $session = new session($database);


  $session->doSomething(); //This method wants to access $database->query();
}
?>

更新(OP 更改了有问题的代码)

<?php

require('class_database.php');
require('class_session.php');

class something
{  
  protected $session = NULL;

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

  public function login() {
    $this->session->doLogin();
  }
}

$database = new database();
$session = new session($database);
$something = new something($session);
$something->login();
?>
于 2012-05-14T07:35:32.437 回答
2

让会话类的构造函数接受一个数据库实例的参数怎么样?

$database = new database();
$session = new session($database);

然后在会话构造函数中,将其设置为对象的属性并使用它:

private var $_database;

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

public function doSomething() {
    $this->_database->query();
}
于 2012-05-14T07:36:39.423 回答