Object Oriented PHP, Class cannot be found

╄→гoц情女王★ 提交于 2021-02-11 18:16:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!