很长一段时间以来,我们的主机服务器遇到了一个非常奇怪的问题。有时(似乎是随机的)PHP中的变量会变成null。
总的来说,一切都很好,但偶尔也会发生这种情况。服务器上的所有帐户和所有PHP应用程序(包括PHPMyAdmin, Wordpress我们自己的脚本)都受到影响。我们联系了我们的托管公司,但他们无法找到任何解决方案。
我没有什么想法,最有希望的是关于Suhosin的问题。但是我没有直接从日志中得到任何消息。
我们编写了一个尽可能简单的脚本来重现这个错误:
<?php
class Example
{
protected $stringVar = 'this is a string value';
public function accessParameter()
{
$error = false;
if (isset($this->stringVar) && !is_null($this->stringVar)) {
echo "string var : " . $this->toStringWithType($this->stringVar) . "'n";
} else {
echo "string var is not set'n";
$error = true;
}
if ($error) {
$logfile = dirname(__FILE__)."/random_bug_log.log";
file_put_contents($logfile, date('Y-m-d H:i:s')."'n", FILE_APPEND);
file_put_contents($logfile, $this->toStringWithType($this->stringVar) . "'n", FILE_APPEND);
}
}
public function toStringWithType($var)
{
$type = gettype($var);
return "($type) '$var'";
}
}
$e = new Example();
$e->accessParameter();
正常输出:string var : (string) 'this is a string value'
奇怪的事情发生时的输出:
string var is not set
我愿意接受任何解决这个问题的想法或建议。我想最终的解决方案是更换托管公司。我没有设法在本地主机或任何其他服务器上创建此问题。
已制作的试件,包括您的建议:
<?php
class Example
{
protected $stringVar = 'this is a string value';
public function accessParameter() {
$error = false;
if(isset($this->stringVar) && !is_null($this->stringVar)) {
echo "string var : "
.$this->toStringWithType($this->stringVar)
."'n";
} else {
echo "string var is not set'n";
$error = true;
}
if($error) {
$logfile = dirname(__FILE__)."/random_bug_log.log";
file_put_contents($logfile, date('Y-m-d H:i:s')." ", FILE_APPEND);
file_put_contents($logfile,
$this->toStringWithType($this->stringVar) . "'n",
FILE_APPEND);
}
}
public function writeParameter() {
$this->stringVar="variable assigned";
if(isset($this->stringVar) && !is_null($this->stringVar)) {
echo "string var : "
.$this->toStringWithType($this->stringVar)
."'n";
} else {
echo "string var is not set'n";
$error = true;
}
}
public function toStringWithType($var)
{
$type = gettype($var);
return "($type) '$var'";
}
}
$e = new Example();
$e->accessParameter();
$e->writeParameter();
事情发生时的输出:
string var is not set
string var is not set
这是个很奇怪的问题。
这可能不是一个解决方案,但值得一试;
protected $stringVar;
function __construct() {
$this->stringVar = 'this is a string value';
}
我建议使用!==而不是is_null来查看变量是否为空。
if (isset($this->stringVar) && ($this->stringVar !== null)) {
或
if (isset($this->stringVar) && (!empty($this->stringVar)) {
对于这些类型的问题,检查if条件中的值,并在else中执行所需操作。就像在你的情况下做的那样:
if(isset($this->stringVar) && ($this->stringVar == "this is a string value")) {
}else{
// your code here...
}