我希望得到关于在PHP中使用类方法的“最佳”方式的意见。
我一直认为这是更好的方式:
class Customer {
public $customer_id;
public $name;
public $email;
public function __construct( $defaults = array() ) {
foreach ( $defaults as $key => $value ) {
if ( property_exists( $this, $key ) ) {
$this->{ $key } = $value;
}
}
}
public function get( $customer_id ) {
$row = ... // Get customer details from database
if ( $row ) {
$this->customer_id = $customer_id;
$this->name = $row['name'];
$this->email = $row['email'];
else {
throw new Exception( 'Could not find customer' );
}
// Don't return anything, everything is set within $this
}
public function update() {
// No arguments required, everything is contained within $this
if ( ! $this->customer_id ) {
throw new Exception( 'No customer to update' );
}
... // Update customer details in the database using
// $this->customer_id,
// $this->name and
// $this->email
}
}
方法论#1。然后将使用这样的类:
$customer = new Customer();
// Get the customer with ID 123
$customer->get( 123 );
echo 'The customer email address was ' . $customer->email;
// Change the customer's email address
$customer->email = 'abc@zyx.com';
$customer->update();
方法论#2。但是,我看到大多数CodeIgniter示例和WordPress示例都使用此类方法:
$customer = new Customer();
// Get the customer with ID 123
$cust = $customer->get( 123 );
echo 'The customer email address was ' . $cust->email;
$cust->email = 'abc@zyx.com';
$customer->update( array( 'customer_id' => 123, 'email' => $cust->email ) );
第二个示例涉及返回对象副本的get
方法,而update
方法需要传入参数而不是使用$this
我不禁觉得第一个例子更干净,更好但也许我忽略了什么?
PS:请忽略以上示例不使用命名空间,设置器,getter等的事实,为了说明的目的,我将它们减少到最小值。