Zdeněk Józsa Zdeněk Józsa - 29 days ago 15
PHP Question

What is a better way to create new object

I have the object

$customer


I need to create new object
$contact
with the contact information
What is a better way to create it?

/** 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;`

Answer

Pre: See this answer for a discussion on using stdClass or an array for holding representative data.

Answer:

  1. The first way is very bad, in that you are adding needless overhead in converting an array to an object (when you could use the array for that purpose).

  2. The second way works, but is not ideal. It does not truly treat the object (in code) as you would treat an object (in life), and therefore does not fit the object-oriented paradigm. (However, it does seem to be the best option for this situation, as per the comments.)

  3. The best way (from an OO perspective) is to define the object class.

Example definition:

 class Contact{
   public $name;
   public $phone;
   public $email;

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

Example instantiation:

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