3

I installed composer and initiate in my project folder. so after installed that /vendor folder created in my project directory by composer.

after that i created two file 1.abc.php 2.demo.php

in abc.php my code is:

namespace abc;
class abc
{
    public function pm()
    {
    echo "test";
    }
}

and my demo.php file code is :

<?php
require_once __DIR__.'/vendor/autoload.php';
use abc\abc;
$abc = new abc();

I just want to access pm() method of 'abc' class using 'namespace' and 'use' method without using this require_once 'abc.php'.

But i getting below error while call demo.php.

Fatal error: Uncaught Error: Class 'abc\abc' not found in /opt/lampp/htdocs/mycomposer/demo.php:8

My File path : opt/lampp/htdocs/php/mycomposer/demo.php
opt/lampp/htdocs/php/mycomposer/abc.php
opt/lampp/htdocs/php/mycomposer/vendor

Any idea please share. Thanks

u_mulder
  • 54,101
  • 5
  • 48
  • 64
Dhaval Vaghela
  • 440
  • 4
  • 20

2 Answers2

4

You can edit your compose.json file and add following

{
    "autoload": {
        "psr-4": {
            "abc\\": "",
        }
    }
}

do

composer update

and test

check https://getcomposer.org/doc/04-schema.md#psr-4 for more details

Jasmin Mistry
  • 1,459
  • 1
  • 18
  • 23
  • thanks for your answer. can you tell why this need to add in composer.json? because if we see in some framework like laravel , magento then its not need to add your custom file class in composer.json. – Dhaval Vaghela Aug 30 '18 at 07:19
  • if u look at composer.json in laravel you see they already have "psr-4": { "": "src/" } declaration in their composer.json to map namespace to path. – Jasmin Mistry Aug 30 '18 at 08:27
-1

You should use require_once to include the files where the class abc resides, and if you succeed, you need to take a closer look at how autoload.php works.

toby
  • 7
  • 2
  • 1
    Hi @toby, thank you for your contribution. however OP is using composer to handle class auto-loading. this is a nice technology to make live easier™. see the [QA posted by u_mulder regarding PSR-4 and Composer](https://stackoverflow.com/questions/28607674/psr-4-autoloading-with-composer). – Bagus Tesa Aug 30 '18 at 06:48
  • PSR-4 is not a framework in sense like symfony or Code Igniter, but its a standard (recommendation), see [here](https://www.php-fig.org/psr/). – Bagus Tesa Aug 30 '18 at 06:55