PHP OOP – Returning lastInsertId from two functions

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


Source: oop

Leave a Reply