How could I call my functions inside a class that are located in another file without resorting toinclude
For example I have the test.php file that contains:
<?php
echo Customer::test();
?>
And the file with the class customer
is Customer.class.php and it contains:
<?php
class Customer {
public function test(){
echo "test";
}
}
?>
Is there a method or configuration file where I can define, for example, that when I call a class, it looks in a folder called classes for example?
Through PSR-4 which is a specification 1 for class autoloading
Important note
Inside your PHP project at the root level, execute the following command:
With this command you will generate a file called
composer.json
which you must fill with the requested data.composer.json
You should have a structure similar to the following, especially check what is after the key
require
Explanation
App
it is the main namespace that will encompass your development and that will identify the classes that are contained in your folderclases
; then every file that exists insideclases
must be preceded by that value like so:Class1.php
namespaceApp;
Class2.php
namespace App
clases
It is the physical path, that is, the folder that will contain all your classes to use.Inside your classes folder generate the file called
Customer.php
which should look more or less like this:Now we must generate the vendor folder with the following command:
The previous command is going to take care of registering our namespace
App
that points to our folderclases
inside an array like the following:Once the above is done, in the root of your project, create your file called test.php and inside it write the following:
Customer
via its full namespace which isApp\Customer
remembered toApp
be the namespace bound to the folderclases
we want to extract to fromCustomer.php
.require
toautoload.php
where, although you must still require it, it will only be a file that in turn manages all the files in the folder belowclases
References