0

I have this script:

<?php
error_reporting(E_ALL);
require 'vendor/autoload.php';

use Church\Config;
use Church\SQLiteConnection;
use Church\Template;
use Church\User;
$ERROR = "";

if(isset($_POST['username']) && isset($_POST['username']))
{
  $login = new User((new SQLiteConnection())->connect());
  if($login->loginUser($_POST['username'], $_POST['password']))
  {

  }
  else {
    $ERROR = "login";
  }
}

if(isset($_GET['go']))
{

}
else {
  if (!file_exists(Config::PATH_TO_SQLITE_FILE)) {
    include('init/install.php');
  }
}

When I make it with this part:

include('init/install.php');

instead of this:

$tpl = new Template('templates/install.tpl');
$tpl->set('HEADER', $tpl->getFile('templates/header.tpl'));
$tpl->set('FOOTER', $tpl->getFile('templates/footer.tpl'));
$tpl->set('APP_NAME', Config::APP_NAME);
$tpl->set('APP_VERSION', Config::APP_VERSION);
$tpl->set('BASE_URL', $_SERVER['PHP_SELF']);
$tpl->render();

I get this error:

Fatal error: Uncaught Error: Class 'Template' not found in

I do not understand why it is working without include but with include is the auto loading not working. What did I miss?

codedge
  • 4,754
  • 2
  • 22
  • 38
beli3ver
  • 363
  • 3
  • 15
  • 3
    You should probably get familiar how [composer autoload](https://stackoverflow.com/questions/12818690/using-composers-autoload) works. – codedge May 04 '20 at 13:55
  • [This could help you](https://stackoverflow.com/a/25138965/3536236) – Martin May 04 '20 at 13:59
  • If you want to use Composer autoload you need to comply with [PSR-4](https://www.php-fig.org/psr/psr-4/) naming conventions. Otherwise, you need to write your own auto-loader (although you can try and plug it into Composer, but you need to configure it properly). – Álvaro González May 04 '20 at 13:59
  • The OP has not mentioned or referenced composer. Why is everyone going on about it? – Martin May 04 '20 at 13:59
  • 1
    @codedge thanks I could fix is with your hint. – beli3ver May 04 '20 at 14:43
  • How does that file in question look like? Is it probably missing the `use` statements? – Nico Haase May 04 '20 at 14:43
  • @Martin We've all assumed it from the `vendor/autoload.php` include and lack of any other reference to class loading. – Álvaro González May 04 '20 at 15:00

1 Answers1

2

Take a look at the docs here: https://www.php.net/manual/en/language.namespaces.importing.php

The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped. The following example will show an illegal use of the use keyword:

And then:

Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules.

The conclusion is that you can't do what you want to do. You need to import (aka use) in your included file too.

Felippe Duarte
  • 14,901
  • 2
  • 25
  • 29