基於你如何使用它(創建Meal
對象的數組,該方法應被聲明爲static
方法,稱爲無$this
上下文中的環可以創建。通過new self()
Meal
對象和附加到陣列之前設置相應的屬性。
如果你仔細想想,這種方法的目的不是爲了作用於單一Meal
,因此它是有道理的,它是static
。
由於它被稱爲無$this
背景下,您將需要通過庫MySQLi連接作爲參數
public static function loadMeals($conn) {
// Do the query/fetch like you already have
// except that $conn is a local param, not a class prop.
$stmt = $conn->prepare("SELECT id, dishName, ingredients FROM meals");
$stmt->execute();
$stmt->bind_result($id, $dishName, $ingredients);
$meals = array();
while ($stmt->fetch()) {
// Create a new Meal object
$meal = new self();
// And set its properties
$meal->id = $id;
$meal->dishName = $dishName;
$meal->ingredients = $ingredients;
// Append it to the array
$meals[] = $meal;
}
// Return it
return $meals;
}
要使用它,在類的外部:
// Call the function statically.
// You'll need to pass the database connection to it
$meals = Meal::loadMeals($conn);
我將指出儘管在做prepare()/execute()
的習慣是非常好的,但實際上並不需要它,因爲您沒有將任何輸入傳遞給查詢。您可以致電$conn->query()
,從MySQLi的bind_result()
變量引用中消除一些複雜性。
$result = $conn->query("SELECT id, dishName, ingredients FROM meals");
if ($result) {
// Fetch and instantiate a Meal object in one go.
while ($meal = $result->fetch_object('Meal')) {
$meals[] = $meal;
}
}
你可以從'Meal'類中發佈'__construct()'嗎? –
好的謝謝 - 我想驗證你的構造函數沒有使用額外的參數,所以Meal可以很容易地實例化。 –