php using 引入新类,正確使用php中其他類的類? - Properly using classes in other classes in php? - 开发者知识库...

12

There are a couple of ways of doing that. Global variables is certainly one way and the most looked down upon too. You can create a Singleton and all other classes that need database access would call upon this singleton.

有幾種方法可以做到這一點。全局變量當然是一種方式,也是最容易被忽視的方式。您可以創建一個Singleton,所有其他需要數據庫訪問的類都會調用此單例。

final class Database {

private static $connection;

public static function getInstance() {

if(self::$connection == NULL) {

self::$connection = // init your database connection

}

return self::$connection;

}

}

And use this database connection object in whatever class needs it.

並且在任何類需要它時使用此數據庫連接對象。

class Application {

public function displayVar() {

echo 'hello world';

}

public function getVar() {

$db = Database::getInstance();

$sql = foo;

$db->query($sql);

}

}

This is all well for a start and a great step beyond using global variables, but you can do better with Dependency Injection. Dependency Injection is a simple concept that if a class has any external dependencies, such as the database connection in your example, you explicitly pass those to the needy class in its constructor or a method. So the new code would look something like Jonathan's solution. A major advantage of using dependency injection is in unit testing, where you can easily replace this actual database object with a mock object and pass it to whoever needs it.

除了使用全局變量之外,這一切都很好,但是你可以使用依賴注入做得更好。依賴注入是一個簡單的概念,如果一個類有任何外部依賴項,例如你的例子中的數據庫連接,你可以在它的構造函數或方法中將它們顯式傳遞給貧困類。所以新代碼看起來像Jonathan的解決方案。使用依賴注入的一個主要優點是單元測試,您可以使用模擬對象輕松替換此實際數據庫對象,並將其傳遞給任何需要它的人。

class Application {

private $db;

public function __construct(Database $db) {

$this->db = $db;

}

public function displayVar() {

echo 'hello world';

}

public function getVar() {

$sql = foo;

$this->db->query($sql);

}

}

For smaller projects, you can easily do it yourself. For large projects, there are various DI frameworks available for PHP

對於較小的項目,您可以輕松地自己完成。對於大型項目,有各種可用於PHP的DI框架

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值