0

I'm new to OOP and have a question regarding functions returning something with the same variable name, for example below:

class CompanyManager
{
   function createCompany()
   {
       // PDO - create the company
       return $db->lastInsertId();
   }

   function createCompanyContact()
   {
       // PDO - create the contact
       return $db->lastInsertId();
   }

}

The problem is I call createCompany first, get it's ID and use that when I create a contact. However in createCompanyContact, if the query fails for any reason it returns the companyID as that was the value previously returned from the database in createCompany and is therefore still set. How do I get around this?

I thought about creating a separate class just for contacts, but surely it is a bit limited if inside a class we are only able to use lastInsertID once (as that value will bleed over to any other functions within it)?

Loop77
  • 98
  • 6

1 Answers1

1

Since you know the problem already, why not just go ahead and put a condition on your second function to only return lastInsertId() if the query did in fact insert a row . For example

 function createCompanyContact()
   {
       // execute the statement here
       if($sth->rowCount()>0)
         return $db->lastInsertId();
       else
         return NULL;
   }
Hanky Panky
  • 46,730
  • 8
  • 72
  • 95