Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我想在PHP中生成顺序ID,唯一但不是随机的_Php - Fatal编程技术网

我想在PHP中生成顺序ID,唯一但不是随机的

我想在PHP中生成顺序ID,唯一但不是随机的,php,Php,我想在PHP中生成顺序ID,例如:EmployeeID、CustomerID等。我们在Java中使用“static”变量,在Python中使用Class变量来生成顺序ID,其中保存最后一个增量的值。我想在PHP中做同样的事情。怎么可能呢?我发现PHP中的“STATIC”关键字与Java中的用法不完全相同 以下是我的Java代码: class演示类{ 专用静态整数计数器=1000; 公共类(){ System.out.println(“对象:+++this.counter); } } 公开课演示{

我想在PHP中生成顺序ID,例如:EmployeeID、CustomerID等。我们在Java中使用“static”变量,在Python中使用Class变量来生成顺序ID,其中保存最后一个增量的值。我想在PHP中做同样的事情。怎么可能呢?我发现PHP中的“STATIC”关键字与Java中的用法不完全相同

以下是我的Java代码:

class演示类{
专用静态整数计数器=1000;
公共类(){
System.out.println(“对象:+++this.counter);
}
}
公开课演示{
公共静态void main(字符串参数[]){
DemoClass a=新的DemoClass();
DemoClass b=新的DemoClass();
DemoClass c=新的DemoClass();
}
}
我想用PHP做同样的事情。下面是我做错的代码。请帮助我,我已经搜索了很多,但没有找到一个合适的解决方案,这个问题

以下是我的PHP代码:

class员工{
私人$姓名$地址;
私人$empid;
专用静态$counter=1000;
公共函数构造($name,$address){
$this->name=$name;
$this->address=$address;
$this->empid=+$this->counter;
}
公共函数displayDetail(){
回显“员工姓名:”.$this->Name.“
”; 回显“员工地址:“$this->Address.”
“; 回显“员工ID:”.$this->empid; } } $emp=新员工(“Indranil Das”,“421纳巴利”); $emp1=新员工(“伦蒂达斯”,“422纳巴利”); $emp->displayDetail(); $emp1->displayDetail();
此代码没有给出我想要的结果。

来自:

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

你可以试试看

Employee::counter

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

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

$this->empid = ++$this->counter;
以下任何一项:

$this->empid = ++self::$counter;
$this->empid = ++static::$counter;
$this->empid = ++Employee::$counter;
self
引用当前类的属性
static
引用层次结构中定义属性/方法的第一个类。类名指的是特定的类

即使它们在您的情况下都工作相同,
self
将是我在本例中的选择,因为它是最简单的一个


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

这里可以像这样删除静态:
private$counter=1000谢谢。事实上,我是PHP新手。这对我有用。