从另一个类访问类变量

时间:2012-05-14 07:32:12

标签: php oop

我对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

我为自己制造了一个我应该避免的麻烦吗?我想要会话提供登录验证,需要访问数据库来检查凭据。

感谢您的帮助

2 个答案:

答案 0 :(得分: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();
?>

答案 1 :(得分:2)

如何使会话类的构造函数采用作为数据库实例的参数?

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

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

private var $_database;

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

public function doSomething() {
    $this->_database->query();
}