You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP+Smarty环境报错:未找到Smarty类,寻求解决方法

问题:Smarty类未找到错误

我是PHP和.tpl模板的新手,找到一份模板后,启动XAMPP的Apache服务器,访问localhost/terminal时出现以下错误:

Fatal error: Uncaught Error: Class "Smarty" not found in C:\xampp\htdocs\terminal\index.php:5 Stack trace: #0 {main} thrown in C:\xampp\htdocs\terminal\index.php on line 5

我已重装XAMPP,也通过Composer在项目目录下载了Smarty,但错误依旧,原本期望能正常显示首页。

项目目录结构如下:
目录结构截图

index.php代码:

<?php
require_once 'vendor/autoload.php'; // Include Composer's autoload file

// Initialize Smarty
$smarty = new Smarty();

// Example usage
$smarty->setTemplateDir('templates/');
$smarty->assign('name', 'World');
$smarty->display('index.tpl'); // Make sure 'index.tpl' exists in 'templates/'

// Optional: Output a simple message
echo "Smarty is set up and running!";
?>

抱歉,这是我第一次提问,若有表述不当之处请见谅。


解决方案
  • 确认Composer安装结果
    检查项目根目录的vendor文件夹是否存在,且内部有smarty目录和autoload.php文件。如果没有,在项目根目录重新执行composer require smarty/smarty,确保安装过程无报错。

  • 修正autoload文件路径
    将require_once 'vendor/autoload.php';改为绝对路径,避免相对路径问题:

    require_once __DIR__ . '/vendor/autoload.php';
    
  • 检查PHP的include_path配置
    打开XAMPP的php.ini文件(Apache控制面板→Config→PHP(php.ini)),确认include_path包含当前目录,例如:include_path = ".;C:\xampp\php\PEAR",保存后重启Apache。

  • 适配Smarty命名空间
    若安装的是Smarty 3+版本,需使用命名空间:
    方式一:直接实例化带命名空间的类

    $smarty = new Smarty\Smarty();
    

    方式二:先引入命名空间再实例化

    use Smarty\Smarty;
    $smarty = new Smarty();
    
  • 清除缓存并重启服务
    清除XAMPP的PHP缓存,重启Apache服务器,避免缓存导致类加载异常。

内容的提问来源于stack exchange,提问作者Victor Steele

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 06:50:02