PHP usage tips

1.  Instance usage 

Array overwritten after a loop
Error code:
$att = new Attachment();
for ($i=2; $i<=$parts;$i++){
$att->attachmentHeader = imap_bodystruct($imap, $msgno, $i);
$att->attachmentContent = imap_fetchbody($imap, $msgno, $i);
$attachments[$i-2] = $att; 
}
return $attachments;

All the objects in the $attachments actually refer to one instance, and this instance object is overwritten by the last $att value. That is because the instance is defined outside the for loop, and every time when the $att is updated, and the $att is updated. 

Correct code:
for ($i=2; $i<=$parts;$i++){
$att = new Attachment();
$att->attachmentHeader = imap_bodystruct($imap, $msgno, $i);
$att->attachmentContent = imap_fetchbody($imap, $msgno, $i);
$attachments[$i-2] = $att; 
}
return $attachments;

2. Be careful of "space"

When you define a string and set the value of the string, it is most possible that you will typo a "space" there, this bug can always be ignored if you do not have experience to make such a typo before, it takes me 2 hours to figure out this typo.

Comments

Popular posts from this blog

install postgreSQL in ubuntu 16.04

timestamp with 16, 13 and 10 digits to Qlik date

install ipython in Cloudera VM using pip