Question

I'm trying to use a file to setup a database connection with RedBeanPHP that can be included everywhere else. Example:

file1.php

<?php
require_once '../vendor/autoload.php';
use RedBean_Facade as R;
R::setup();
?>

file2.php

<?php
require_once 'file1.php';
R::debug(true);
?>

However navigating to file2.php shows this error:

Fatal error: Class 'R' not found in /file1.php on line 5

Do namespace use statements in PHP not get included?

Was it helpful?

Solution

In PHP namespace and use declarations are only valid in the physical file they appear in. These declarations do not span across requires. They are already handled at compile-time.

If a.php uses aliases in its namespace, and it is included by b.php, the aliases defined in a.php will not be seen by b.php.

You will have to insert your use statement into every file. Here's the documentation:

Importing rules are per file basis

However, you can work around this using class_alias:

class_alias('RedBean_Facade', 'R');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top