請看看這個課程,我知道應用程序之外的一段代碼幾乎沒有告訴我應該做什麼,但我想你明白基本上應該做什麼和被用於什麼。PHP - 從數據庫加載/刪除使用靜態方法或不?
<?php
class Customer
{
const DB_TABLE = 'customers';
public $id = NULL;
//all other properties here
function __construct($associative_array = NULL)
{
//fills object properties using values provided by associative array
}
static function load($customer_id)
{
$obj = new static(); //PHP 5.3 we use static just in case someone in future wants to overide this in an inherited class
//here we would load data from DB_TABLE and fill the $obj
return $obj;
}
static function delete($customer_id)
{
//here we just delete the row in the DB_TABLE based on $customer_id (which is the primary key of the table)
}
function save()
{
//saves $this properties into a row of DB_TABLE by either updating existing or inserting new one
}
}
而且任何類型的評論,你會做的代碼(即總是讚賞),這裏的主要問題是:「已經對SO大約讀了很多周圍多麼糟糕static
方法和使用static
一般情況下,在這段代碼中你會不會使兩種方法load/delete
不是靜態的?如果是的話,你可以用一個小例子來解釋一下。「
這似乎很奇怪我沒有讓他們static
,因爲我認爲這是奇怪,以創建從數據庫加載一個新的對象被迫每次寫:簡單地做
$obj = new Customer(); //creating empty object
$obj->load(67); //loading customer with id = 67
代替
$obj = Customer::load(67); //creates a new customer and loads data form DB
讓我們來談談刪除,你沒有聲明'static'。如果使用你的代碼,我該怎麼做:'$ obj = getCar(78); $ obj-> delete();'我想這會在數據庫中刪除'id = 78'的行,但是刪除後'$ obj'中有什麼?例如:如果在刪除後我會調用'$ obj-> save();' – 2012-01-18 17:46:20
@MarcoDemaio,我通常在我的對象中有一個RESET函數,並且在LOAD/DELETE上調用reset。因此,該對象變成了一個全新的實例。就像我說的,這不一定是最好的方式,但我喜歡它 – 2012-01-18 18:06:39