PHP index not connected to Model class

I'm trying to test it using a simple Example I wrote but the Browser always says :

Fatal error: Uncaught Error: Class 'Model' not found in C:\xampp\htdocs\mvcFirst\index.php:9 Stack trace: #0 {main} thrown in C:\xampp\htdocs\mvcFirst\index.php on line 9

I've searched in internet but didn't found the reason for that. Here is my Code:

  1. Model Class :

    <?php
    
    class Model
    {
        public $string;
        public function __construct()
        {
            $this->string="MVC and PHP are awesome!";
        }
    }
    
  2. Controller Class :

    <?php
    class Controller
    {
        private $model;
        public function __construct($model)
        {
            $this->model=$model;
        }
    }
    
  3. View Class :

    <?php
    class View
    {
        private $controller;
        private $model;
        public function __construct($controller,$model)
        {
            $this->controller=$controller;
            $this->model=$model;
        }
        public  function output(){
            return "<p>".$this->model->string."</p>";
         }
    }
    
  4. index.php :

    <?php
    
    try {
        $model = new Model();
        $controller = new Controller($model);
        $view = new View($controller, $model);
        echo $view->output();
    }catch (Exception $e){
       echo $e->getMessage();
    
    }
    ?>
    

    with any suggestion i'll be Thankful.

1 answer

  • answered 2017-10-11 10:07 OptimusCrime

    In PHP you need to include the external files you wish to use. One way to do this is to use the function include_once and specify each file you want to include in your code.

    Assuming your files are named model.php, controller.php and view.php, you need to put this right after the opening php tag in your index.php file:

    include_once './model.php';
    include_once './controller.php';
    include_once './view.php';
    

    Another way is to apply autoloading. Autoloading is done when PHP encounters a class it has not yet seen, and a class that is not yet loaded. The autoloading is done using the function spl_autoload_register. The official docs contains a very simple illustrative code for how it works:

    <?php
    spl_autoload_register(function ($class_name) {
        include $class_name . '.php';
    });