为什么php';使用';将示例代码放入函数时失败


Why does php 'use' fail when I put example code into a function?

从一些示例代码开始,我不明白为什么这些场景不能全部工作。

名为Script.php的示例代码脚本当从命令行运行时,该文件成功工作

<?php
//Script in standalone file: script.php
//...define some stuff
require REQUIRED_FILE;
use Aws'Ses'SesClient;
//now do some stuff
?>

当我将脚本的内容内联到我的大型程序中时,它在"使用"部分失败。

<?php
//class-of-bigger-program.php
//function called from some other part of program
function foo(){
    //paste the contents of the same script above
    //...define some stuff
    require REQUIRED_FILE;
    use Aws'Ses'SesClient;//CRASH HERE
    // now do some stuff
}
?>

然而,当将脚本包含在较大程序的同一位置时,效果良好。

<?php
//function called from some other part of program
function foo(){
    //paste the contents of the same script above
    include 'script.php';
}
?>

为什么会出现这种情况?我只是错过了使用"use"命令吗?我发现"use"answers"include"以及命名空间之间的区别很难理解。

PHP文档将很好地为您解释这一点。了解为什么你不能做某事通常比仅仅知道你不能做更有帮助。

use关键字必须在文件的最外层范围(全局范围)或命名空间声明内部声明。这是因为导入是在编译时而不是运行时完成的,所以它不能是块范围的。

换句话说,它在运行程序之前导入其他代码,因此它必须位于程序的最外层。

为什么在函数中添加use?如果你的class-of-bigger-program.php真的是一个类,那么你应该做:

require REQUIRED_FILE; 
use Aws'Ses'SesClient; 
class YourClass {...}