0

I have a small task to create a Object Oriented PHP backend application which is to be used by an angular 7 frontend. This is a very small project with only few classes and my php project folder structure looks like,

 wamp/www/MyProject
  - MyObject.php
  - MyParser.php
  - index.php

MyParser class looks like,

<?php
namespace app\parse;

class MyParser
{
    public static function parse_object(){
        echo "in parse_object";
        // --- parse logic---
   }
}

And my index.php file looks like,

<?php

//---- some request processing here ---
use app\parse\MParser;
MyParser::parse_object();
?>

When I try to access index.php from the browser with http://localhost/MyProject/index.php I get,

Fatal error: Uncaught Error: Class 'app\parse\MyParser' not found in C:\wamp\www\MyProject\index.php on line 9
( ! ) Error: Class 'app\parse\MyParser' not found in C:\wamp\www\MyProject\index.php on line 9

It would be highly appreciated if you can find out what I am missing here.

Thudani Hettimulla
  • 754
  • 1
  • 12
  • 32
  • 2
    Are you using some kind of autoloader in your project? If not, you need to include the file containing the MyParser class explicitly, because `use` does not do that for you. Have a look at these questions: [How does the keyword use work in php and can I import classes with it](https://stackoverflow.com/questions/10965454/how-does-the-keyword-use-work-in-php-and-can-i-import-classes-with-it) and [Use vs include as an import statement in php](https://stackoverflow.com/questions/48263687/use-vs-include-as-an-import-statement-in-php). – mrodo Feb 28 '20 at 01:55

1 Answers1

3

In order to be able to use MyParser static method, you need to explicitly require MyParser.php:

<?php

//---- some request processing here ---
use app\parse\MyParser;
require("MyParser.php");
MyParser::parse_object();
?>

If you want to be able to use it without the require, you have to use an autoloader.

toh19
  • 1,083
  • 10
  • 21