Apache2.4+PHP7部署Ajax-Chat遇静态调用及$this上下文错误求助
咱们一步步拆解你遇到的问题,帮你搞定这个报错:
第一个错误的本质
PHP 7 对「静态调用非静态方法」的行为做了严格限制——之前的PHP版本可能只是警告,但PHP7直接抛出Deprecated错误。你看到的Deprecated: Non-static method AJAXChatFileSystem::getFileContents() should not be called statically,就是因为AJAXChatFileSystem::getFileContents()本身不是静态方法,但你在AJAXChatTemplate::getContent()里用了类名直接调用的静态方式。
为什么改static后会触发新错误?
你把getContent()改成public static function getContent()后,静态方法内部是不能用$this的——$this指向的是类的实例对象,而静态方法属于类本身,不需要实例化就能调用,自然没有$this的上下文,所以会爆出Fatal error: Using $this when not in object context。
两种可行的修复方案
方案一:将AJAXChatFileSystem的getFileContents改为静态方法(推荐)
找到AJAXChatFileSystem类所在的文件(一般在lib/class/AJAXChatFileSystem.php),把getFileContents方法修改为静态方法:
public static function getFileContents($filePath) { // 方法内部的原有逻辑保持不变 }
然后把你之前修改的AJAXChatTemplate::getContent()改回原来的非静态版本:
function getContent() { if(!$this->_content) { $this->_content = AJAXChatFileSystem::getFileContents($this->_templateFile); } return $this->_content; }
这样既符合PHP7的静态调用规范,又能正常用$this访问实例属性。
方案二:实例化AJAXChatFileSystem后调用方法(不修改原类的情况)
如果你不想改动AJAXChatFileSystem类,就在getContent()里创建该类的实例,通过实例调用方法:
function getContent() { if(!$this->_content) { // 创建AJAXChatFileSystem实例 $fileSystem = new AJAXChatFileSystem(); $this->_content = $fileSystem->getFileContents($this->_templateFile); } return $this->_content; }
这种方式避开了静态调用非静态方法的问题,也不需要调整getContent()的属性。
验证修复
选一种方案修改后,重启Apache服务器确保代码生效,再访问Ajax-Chat应该就能正常加载模板内容了。
内容的提问来源于stack exchange,提问作者Rohit

