PHP致命错误:在非对象上调用__clone方法

9

我正在开发一个项目,但遇到了错误和警告。由于我对PHP很陌生,所以希望您温柔点。程序在PHP 5.5上运行良好。但当我在PHP 5.6上运行程序时,出现了以下几个错误:

[10-Oct-2016 10:04:46 America/Denver] PHP Warning: Erroneous data format for unserializing 'MMR\Bundle\CodeTyperBundle\Entity\User' in /hermes/bosnaweb14a/b1234/.../application/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php on line 833 [10-Oct-2016 10:04:46 America/Denver] PHP Notice: unserialize(): Error at offset 49 of 50 bytes in /hermes/bosnaweb14a/b1234/.../application/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php on line 833 [10-Oct-2016 10:04:46 America/Denver] PHP Fatal error: __clone method called on non-object in /hermes/bosnaweb14a/b1234/.../application/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php on line 837

项目信息

平台:Symfony PHP版本:5.6

受影响的代码

public function newInstance()
{
    if ($this->_prototype === null) {
        if (PHP_VERSION_ID === 50429 || PHP_VERSION_ID === 50513) {
            $this->_prototype = $this->reflClass->newInstanceWithoutConstructor();
        } else {
           $this->_prototype = unserialize(sprintf('O:%d:"%s":0:{}', strlen($this->name), $this->name)); //Line 833
        }
    }

  return clone $this->_prototype; //Line 837
}

非常感谢您的帮助。


if 之后或作为第二个条件,也要测试 is_object($this->_prototype) - JustOnUnderMillions
您的unserialize失败了,可能是因为PHP Notice: unserialize():的问题。 - JustOnUnderMillions
显然,在$this->name字符串中存在未转义的字符,因此unserialize()函数无法将其解码。 - martin
在php的不同版本中,unserialize的标准是否不同?因为它在5.5版本中正常运行,但在5.6版本中失败了。 - jamHud
2个回答

1
我进行了测试: < p > < code > var_dump(clone $t = unserialize(sprintf('O:%d:“%s”:0:{}',strlen('name'),'name')));

它可以工作。

您必须检查 $this->name 的值,可能为空或包含非法字符。

首先在哪里设置了$this->name


谢谢,我会研究一下。 - jamHud

0
快速修复: 只需在您的if条件中添加一个版本,即PHP 5.6,并且它将是PHP_VERSION_ID === 50640
例如:
    if ($this->_prototype === null) {
        if (PHP_VERSION_ID === 50429 || PHP_VERSION_ID === 50513 || PHP_VERSION_ID === 50640) {
            $this->_prototype = $this->reflClass>newInstanceWithoutConstructor();
        } else {
            $this->_prototype = unserialize(sprintf('O:%d:"%s":0:{}', strlen($this->name), $this->name));
        }
    }

这个答案有点旧了,但我希望它能帮助到未来的某个人;PHP版本ID的最后两位数字可能会很快改变;我目前在本地机器上运行的是80121,但我的Docker环境运行的是80120。对于PHP 5.6,最好检查类似PHP_VERSION_ID >= 50600 && PHP_VERSION_ID < 50700的条件。更好的做法是使用内置的version_compare函数! - Fons

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接