【问题标题】:What is a better way to create new object什么是创建新对象的更好方法
【发布时间】:2017-03-23 18:56:31
【问题描述】:

我有对象$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;`

【问题讨论】:

  • 第二种方式当然更容易阅读。
  • 第二,因为不需要转换
  • $contact = clone $customer; 怎么样?

标签: php object


【解决方案1】:

Pre:有关使用 stdClass 或数组保存代表性数据的讨论,请参阅 this answer

答案:

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

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

  3. 最好的方法(从 OO 的角度来看)是定义对象类。

示例定义:

 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);

【讨论】:

  • 谢谢你的回答,但我使用的框架我不想定义自己的类。顺便提一句。为什么你定义了函数Contact而不使用函数__construct?
  • @AbraCadaver 说 OO 设计原则。
  • @ZdeněkJózsa 您打算将方法放入对象中吗?还是只有数据?
  • @Kittsil 仅数据(上面代码中的三个值)。
  • @ZdeněkJózsa 您是否有理由不能将数据简单地视为数组?
猜你喜欢
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
  • 2014-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
相关资源
最近更新 更多