简体   繁体   English

PHP OOP-从两个函数返回lastInsertId

[英]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: 我是OOP的新手,并且对函数返回具有相同变量名的东西有疑问,例如:

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. 问题是我先打电话给createCompany,获取它的ID并在创建联系人时使用它。 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. 但是,在createCompanyContact中,如果查询由于任何原因而失败,它将返回companyID,因为该ID是先前从createCompany中的数据库返回的值,因此仍被设置。 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)? 我曾考虑过为联系人创建一个单独的类,但是如果在一个类中我们只能使用一次lastInsertID(因为该值将渗入其中的任何其他函数),那么肯定会有所限制吗?

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 . 既然您已经知道了问题,那么为什么不继续进行操作,并在第二个函数上加一个条件,如果查询确实插入了row,则仅返回lastInsertId() For example 例如

 function createCompanyContact()
   {
       // execute the statement here
       if($sth->rowCount()>0)
         return $db->lastInsertId();
       else
         return NULL;
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM