在PHP中使用类方法的最佳方法

在PHP中使用类方法的最佳方法,php,codeigniter,oop,Php,Codeigniter,Oop,我想了解在PHP中使用类方法的“最佳”方法 我一直认为这是更好的方式: class Customer { public $customer_id; public $name; public $email; public function __construct( $defaults = array() ) { foreach ( $defaults as $key => $value ) { if ( propert

我想了解在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:请忽略以上示例不使用名称空间、setter、getter等的事实,为了便于说明,我已将它们缩减到最小值

第二个允许您应用流畅的界面第二个允许您应用流畅的界面