包含文件中的PHP变量范围


PHP Variable Scope Inside Included Files

我有以下代码:

<?php
session_start();
require_once('ClassFile.php');
use ClassFile'Component;
include 'somefile.php';
?>

在这个模板中,我可以访问组件的属性(例如$comp=new Component();)。但是,组件在somefile.php中不可见。我得到一个错误,大意是它不存在。(糟糕的)解决方法是在somefile.php中复制相同的代码。有人能说出发生了什么吗?我是否需要以某种方式将require_one和use语句中的项全局化?谢谢

如果您的意思是不能在somefile.php中执行new Component,那是因为该类被称为ClassFile'Component,而不是Componentuse别名不扩展到包含的文件。如果您也想在somefile.php中将ClassFile'Component别名为Component,则还必须在该文件中编写相应的use语句。

名称间距始终为每个文件。