PHP+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

