Search code examples
phpinheritancecomposer-phpautoloader

PHP - Extend classes using composer autoloader causes redeclare error


I'm just learning how to use composer for my own classes. So I've this ditectory structure

I'm using PHP version 5.5.30 and Composer 1.1.0

  • Pdf
    • test.php
    • composer.json
    • vendor/
      • autoload.php
      • jarouche/
        • jarouche.php
        • jarouche2.php

So, I have

  test.php
  <?php
      require_once('vendor/autoload.php');
      use jarouche\jarouche2;

      $teste = new jarouche2();
      $teste->teste();
   ?>

   jarouche.php

   <?php

       namespace jarouche;

       class jarouche{

           public function teste(){
               echo 'jarouche';
           }

        }
   ?>

  jarouche2.php

   <?php

       namespace jarouche;

       class jarouche2 extends jarouche{

           public function teste(){
               echo 'jarouche2';
           }

        }
   ?>

  composer.json

  {
    ...

          "autoload": {
                        ...
                        "psr-4": {"jarouche\\": "vendor/jarouche"
           }
   }

But, when I run test.php I got this error "Fatal error: Cannot redeclare class jarouche\jarouche2 in C:\xampp\htdocs\Pdf\vendor\jarouche\jarouche2.php on line 6"

I've tried putting a if (!class_exists('MyClass')) in jarouche2.php, tried to update composer... nothing worked.

What's my mistake?


Solution

  • For some reason I did a composer self-update and now it's working!