PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, January 20, 2022

[FIXED] PHP - Namespace isn't working properly

 January 20, 2022     composer-php, namespaces, php, runtime-error     No comments   

Issue

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.


Solution

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



Answered By - Matteo
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing