JRomeo
JRomeo

Reputation: 533

PHP Variable Scope Inside Included Files

I have the following code:

<?php

session_start();
require_once('ClassFile.php');
use ClassFile\Component;

include 'somefile.php';

?>

Within this template I can access properties of the Component (e.g. $comp = new Component();). However, Component is not visible from within somefile.php. I get an error to the effect that it does not exist. The (poor) workaround is to copy the same code in somefile.php. Can anyone say what's going on? Do I need to somehow globalize the items in the require_once and use statements? Thanks.

Upvotes: 0

Views: 54

Answers (1)

deceze
deceze

Reputation: 522081

If you mean that you cannot do new Component inside somefile.php, that's because the class is called ClassFile\Component, not Component. The use alias does not extend to included files. If you want to alias ClassFile\Component to Component in somefile.php too, you have to write the appropriate use statement in that file too.

Namespacing is always per-file.

Upvotes: 2

Related Questions