這裏是我爲什麼要嵌套的示例類。php中的嵌套類
include("class.db.php");
class Cart {
function getProducts() {
//this is how i do it now.
//enter code here`but i dont want to redeclare for every method in this class.
//how can i declare it in one location to be able to use the same variable in every method?
$db = new mysqlDB;
$query = $db->query("select something from a table");
return $query
}
}
我會建議不要這樣做,因爲如果您已經在代碼的另一部分連接到數據庫,或者想要製作多個購物車,它會是一個問題。使用下面的答案,因爲它通過構造函數注入依賴項。 – 2010-05-14 17:10:07