【发布时间】:2012-01-17 19:36:30
【问题描述】:
请看一下这个类,我知道应用程序之外的一段代码几乎没有说明应该做什么,但我认为你了解基本上应该做什么和用于做什么。
<?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
}
}
除了您将在代码上制作的任何类型的 cmets(总是受到赞赏)之外,这里的主要问题是:“在 SO 上阅读了很多关于 static 方法和用法有多糟糕的信息一般来说static,在这段代码中,你会让load/delete这两个方法不是静态的吗?如果是,为什么,你能用一个小例子解释一下。”
我觉得不让它们static 看起来很奇怪,因为我认为创建一个从 DB 加载的新对象以强制每次都写入是很奇怪的:
$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
【问题讨论】: