面向对象的 PHP,找不到类 [英] Object Oriented PHP, Class cannot be found
问题描述
我有一个小任务来创建一个面向对象的 PHP 后端应用程序,该应用程序将由 angular 7 前端使用.这是一个非常小的项目,只有几个类,我的 php 项目文件夹结构看起来像,
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 类看起来像,
MyParser class looks like,
<?php
namespace app\parse;
class MyParser
{
public static function parse_object(){
echo "in parse_object";
// --- parse logic---
}
}
我的 index.php 文件看起来像,
And my index.php file looks like,
<?php
//---- some request processing here ---
use app\parse\MParser;
MyParser::parse_object();
?>
当我尝试使用 http://localhost/MyProject/index.php 从浏览器访问 index.php 时我明白了,
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.
推荐答案
为了能够使用 MyParser
静态方法,您需要显式地 require MyParser.php
:
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.
这篇关于面向对象的 PHP,找不到类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!