问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/60444168/object-oriented-php-class-cannot-be-found