我想用PHP生成序列ID,唯一但不是随机的


I want to generate sequential ID in PHP, unique but not random

我想在PHP中生成序列ID,例如:EmployeeID、CustomerID等。我们在Java中使用"static"变量,在Python中使用class变量来生成包含上次增量值的序列ID。我想在PHP中做同样的事情。这怎么可能?我发现PHP中的"STATIC"关键字和Java中的用法并不完全相同。

这是我的Java代码:

class DemoClass{
   private static int counter=1000;
   public DemoClass(){
     System.out.println("Object: " + ++this.counter);
   }
}
public class Demo {
  public static void main(String args[]){
    DemoClass a = new DemoClass();
    DemoClass b = new DemoClass();
    DemoClass c = new DemoClass();
  }
}

我想在PHP中做同样的事情。以下是我做错的代码。请帮忙我找了很多,但没有找到解决这个问题的合适方法。

这是我的PHP代码:

class Employee{
private $name, $address;
private $empid;
private STATIC $counter = 1000;
public function __construct($name, $address) {
     $this->name = $name;
     $this->address = $address;
     $this->empid = ++$this->counter;
 }
public function displayDetail() {
    echo "Employee Name: " . $this->name."<br>";
    echo "Employee Address: " . $this->address."<br>";
    echo "Employee ID: " . $this->empid;
  }
}
$emp = new Employee("Indranil Das", "421-Nabapally");
$emp1 = new Employee("Ronty Das", "422-Nabapally");
$emp->displayDetail();
$emp1->displayDetail();

这个代码没有给我想要的结果。

在PHP中,不能访问对象上下文中的static类属性。您需要使用selfstatic关键字或类名,再加上::运算符,而不是->,而不是使用$this

因此,在您的示例中,更改以下行就足够了:

$this->empid = ++$this->counter;

到以下任何一个:

$this->empid = ++self::$counter;
$this->empid = ++static::$counter;
$this->empid = ++Employee::$counter;

self是指当前类的一个属性。static指的是层次结构中定义属性/方法的第一个类。类名指的是特定的类。

尽管它们在您的情况下都是一样的,但在本例中,self将是我的选择,因为它是最简单的一个。

您可以在文档中阅读更多关于PHP中静态属性和方法的信息。

来自文档:

无法使用箭头运算符->通过对象访问静态属性。

你可以试着做

Employee::counter

以访问变量。