3

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;`
j08691
  • 204,283
  • 31
  • 260
  • 272

1 Answers1

1

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);
Community
  • 1
  • 1
Kittsil
  • 2,349
  • 13
  • 22
  • Thank you for the answer, but I use the framework where I don't want to define own classes. Btw. why did you define the function Contact and did not use function __construct? – Zdeněk Józsa Nov 09 '16 at 21:03
  • @AbraCadaver Says OO design principles. – Kittsil Nov 09 '16 at 21:07
  • @ZdeněkJózsa Are you planning to put methods in the object? Or only data? – Kittsil Nov 09 '16 at 21:08
  • @Kittsil Only data (three values in the code above). – Zdeněk Józsa Nov 09 '16 at 21:11
  • @ZdeněkJózsa Is there a reason you can't treat the data simply as an array? – Kittsil Nov 09 '16 at 21:13
  • @Kittsil Yes - in the Nette framework I can send only object to the framework frontend template. – Zdeněk Józsa Nov 09 '16 at 21:19
  • In that case, I'd go with the second option; it is cleaner and should be faster (although I do not usually benchmark `php` code). But I protest that, from a software design perspective, this question feels like asking, "Is it better to smash my toe or my finger with a hammer?" – Kittsil Nov 09 '16 at 21:27
  • @Kittsil Thank you for your discussion. – Zdeněk Józsa Nov 09 '16 at 21:30
  • @ZdeněkJózsa I forgot the link to the other answer; it has been added. It might be worth supplementing your question with why a) you need to put your data into an object and b) you can't store it in a data array. – Kittsil Nov 09 '16 at 22:43