Chris Chris - 7 months ago 9
PHP Question

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

Having started from some example code, I don't understand why these scenarios don't all work.

Script of example code called script.php the file successfully works when run from command line

<?php
//Script in standalone file: script.php

//...define some stuff
require REQUIRED_FILE;
use Aws\Ses\SesClient;
//now do some stuff
?>


When I inline the contents of the script into my large program it fails on the 'use' part.

<?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
}
?>


However when including the script in the same place of that larger program it works fine.

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


Why is this the case? Am i just miss using the 'use' command?
I have found the differences between 'use' and 'include' and namespaces hard to understand.

Answer

Why do you add the use in the function? If your class-of-bigger-program.php is really a class, then you should do:

require REQUIRED_FILE; 
use Aws\Ses\SesClient; 

class YourClass {...} 
Comments