5

I have a class that is declared in my application that has a private static member like so:

class SomeClass{
private static myMember =  array(); 

public static getterFunction(){}
public static setterFunction(){}

}

My question / concern is that multiple requests (i'm thinking like a thread in Java) would be able to modify this static member. My understanding of php scope and static members is that they are in the request scope and a new variable is created for each new request and subsequently destroyed after the request has been fulfilled. That said, this would be a difficult thing to test (at least i can't think of an easy way) so i'd rather be safe than sorry.

Is my assessment correct? The PHP docs i've read are pretty crappy in terms of detail so I haven't been able to authoritatively answer yet...

4

2 回答 2

5

除非您明确地这样做(例如使用会话、数据库、文件、共享内存),否则没有任何数据是持久的或在 PHP 脚本的不同实例之间共享。每个 PHP 实例都是它自己的东西,每个新请求都会导致 web 服务器启动一个单独的实例。

所以是的,你是对的。

于 2012-12-13T18:00:45.123 回答
0

默认情况下,您在 PHP 中没有共享内存。每个请求都在单独的进程中处理,因此它们彼此不知道。

我希望我正确理解了你的问题。

例如:

您有一个简单的 script.php 文件,它在传递 GET 参数时在类中设置私有字段:

<?
class A {
  private $x = 1;
  public function setX($x) {$this->x = $x;}
  public function getX() {return $this->x;}
}

$a = new A();
if (!empty($_GET['x'])) {
  $a->setX($_GET['x']);
  sleep(3);
}

echo $a->getX();
?>

您一次执行两个请求:

GET /script.php?x=5
GET /script.php

第二个请求将打印您“1”。是的,你是对的!

于 2012-12-13T18:06:53.717 回答