创建新对象的更好方法是什么?


What is a better way to create new object

我有一个对象$customer

我需要用联系人信息创建新对象$contact有什么更好的方法来创造它?

/** the first way */
$contact = (object) array('name' => $customer->name, 'phone' => $customer->phone, 'email' => $customer->email);
/** the second way */
$contact = new stdClass();
$contact->name = $customer->name;
$contact->phone = $customer->phone;
$contact->email = $customer->email;`

Pre:有关使用stdClass或数组保存代表性数据的讨论,请参阅此回答。

答:

  1. 第一种方法非常糟糕,因为在将数组转换为对象时增加了不必要的开销(当您可以为此目的使用数组时)。

  2. 第二种方法有效,但并不理想。它并没有像对待对象(在生活中)那样真正地对待对象(在代码中),因此不适合面向对象范式。(然而,根据评论,这似乎是这种情况下的最佳选择。)

  3. 最好的方法(从面向对象的角度)是定义对象类。

示例定义:

 class Contact{
   public $name;
   public $phone;
   public $email;
  function __construct($name, $phone, $email) {
    $this->name = $name;
    $this->phone = $phone;
    $this->email = $email;
  }
}

示例实例化:

$contact = new Contact($customer->name, 
  $customer->phone,
  $customer->email);