This is my project path configuration
./create.php
/Install/Install.php
create.php
<?php
use InstallInstall;
echo "Starting";
$install = new Install();
This gives me the error
PHP Fatal error: Uncaught Error: Class ‘InstallInstall’ not found in /project/create.php:6
Install.php
<?php
namespace Install;
class Install
{
//whatever
}
Can someone explain me what is happening there ?
Obviously I guess that using a require_once
line with my filename would probably fix the issue…but I thought using namespace and use import could prevent me from doing that like we do in classic framework like symfony / magento ?
I’ve seen some post speaking about autoloading, but i’m a little bit lost. Haven’t been able to find a clear explanation on the other stack topic neither.
2
Answers
If you want to Use class from another file, you must
include
orrequire
the file.Use
require('Install.php');
beforeuse InstallInstall;
.If you are planning to do a big project I would recommend to use PHP frameworks rather than coding from scratch.
PHP compiles code one file at a time. It doesn’t have any native concept of a "project" or a "full program".
There are three concepts involved here, which complement rather than replacing each other:
Install
and still tell the difference between them. Theuse
statement just tells the compiler (within one file) which of those classes you want when you writeInstall
. The PHP manual has a chapter on namespaces which goes into more detail on all of this.spl_autoload_register
will be called with that class name, and then has a chance to run include/require to load the definition. There is a fairly brief overview of autoloading in the PHP manual.So, in your example:
use InstallInstall;
just means "when I writeInstall
, I really meanInstallInstall
"new Install()
is translated by the compiler tonew InstallInstall()
InstallInstall
hasn’t been defined; if an autoload function has been registered, it will be called, with the string "InstallInstall" as inputrequire_once __DIR__ . '/some/path/Install.php';
You can write the autoload function yourself, or you can use an "off-the-shelf" implementation where you just have to configure the directory where your classes are, and then follow a convention for how to name them.