Phoenix404
Phoenix404

Reputation: 1058

PHP - Namespace isn't working properly

I am using xampp on windows 7 with php 5.6.24. I have problem with php Namespace.

My project direcotry look like this :

-project
 + config
 - Framework
   + database
   + Expection
   test.php
 + src
 index.php

I have php file inside Framework/test.php and it contains the following code :

<?php
namespace Framework\Test;
echo " i  Am in test.php class";
class Test{
    public function __construct(){
        echo "I m from test classs ";
    }

    public function test_method(){
        echo " No";
    }
}

In my root directory i have index.php, composer.json

My composer.json has autoload object

  "autoload": {
    "psr-4": {
      "Framework\\": "Framework/"
    },
    "files": [
        "src/Helpers/ArrayHelpers.php"
    ]
  },

In my index.php, i have following code :

<?php
echo "<pre>";

require __DIR__ . '/vendor/autoload.php';
use Framework\Test;
$n      = new Test;
print_r($n);

When i run index.php file on browser i get the responce :

i Am in test.php class;

Fatal error: Class 'Framework\Test' not found in C:\xampp\htdocs\project\index.php on line 12

I don't know what i am doing wrong ? Is my namespace is wrong ? But i am getting echo from that file how ? why ? whats going wrong ? is my composer file wrong ?

Thanks in advance.

Upvotes: 3

Views: 3399

Answers (1)

Matteo
Matteo

Reputation: 39390

The namespace of the class Test is simply Framework, (because it is located in the Framework folder also) so try to change the Test.php as follow:

<?php
namespace Framework;
echo " i  Am in test.php class";
class Test{
    public function __construct(){
        echo "I m from test classs ";
    }

    public function test_method(){
        echo " No";
    }
}

Hope this help

Upvotes: 1

Related Questions