Search code examples
phpparse-errorpsr-4

Unable to autoload a php class using psr-4


I am trying to use psr-4 to autoload a class but the more I try, no results I find. I don't really know how to work with psr-4 and i am so dumb finding how to fix the error. My code structure is as follows:
-project-root
--app
---class
----init.php

--vendor
--index.php

The composer.json code is:

"autoload": {
    "psr-4": {
        "App\\" : "app/"
    }
}

The following is app/class/init.php:

<?php
namespace App\class;

class Connect
{
    public function connect ()
    {
        echo 'hello';
    }
}

And here is my index.php contents:

<?php
require_once('vendor/autoload.php');
use App\class\Connect as connector;

$obj = new connector;
$obj->connect();


The code stops running with the following error :

Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or '{' in C:\xampp\htdocs\test\index.php on line 3 Would you please help me to understand where and what my error in writing autoloading related code is? Thank you very much in advance.


Solution

  • class is a keyword in PHP. Try to rename directory and respectively name of the namespace (App\class) for example to App\classes.