【发布时间】:2013-05-09 23:22:26
【问题描述】:
很长一段时间以来,我们的托管服务器遇到了一个非常奇怪的问题。有一段时间(似乎是随机的)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
我愿意接受有关如何解决此问题的任何想法或建议。我想最终的解决方案是改变托管公司。我没有设法在 localhost 或任何其他服务器上创建此问题。
已制作的测试件,包括您的建议:
<?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
【问题讨论】:
-
这是一个非常奇怪的案例。我建议看看他们是否可以更换您的服务器而不是更换公司,这可能是一些间歇性硬件故障或内存芯片即将发生故障的迹象
-
isset — Determine if a variable is set and is not NULLsee here。所以你不需要is_null检查。 -
我也遇到过奇怪的问题,比如随机
strpos返回false... -
@Amir 是的,如果不检查 Notice,您无法将
NULL与 Undefined 区分开来。 -
@zupapomidorowa - 如果您在某处写入变量(目前它是静态的),是否也会出现此问题?
标签: php variables null hosting