PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, January 6, 2022

[FIXED] How to include class?

 January 06, 2022     autoload, composer-php, php     No comments   

Issue

handlers/
     handler.php
src/
     Model.php

I'm trying include class Model.php

<?php 
declare(strict_types=1);

namespace App;

class Model{
    }

handler.php

<?php 
include_once($_SERVER['DOCUMENT_ROOT'].'/src/Model.php');

$model=new Model();

I get an error:

Class 'Model' not found

Is it because I am using composer autoloader?

"autoload": {
        "psr-4": {
            "App\\": ["src/"]


        }
    },

Solution

Model.php

<?php 

declare(strict_types=1);

namespace src;

class Model{}

Handler.php

<?php 
    
use src\Model;

require __DIR__ . '../vendor/autoload.php'; // or whatever to route is to your autoload file

$model=new Model();

The final thing I want to mention is that the directory specified in the autoload file should be a folder that contains all of your classes ideally. Beyond that, the namespaces should be subdirectories in the directory where that class can be located. So say you have the folder Classes, and then src may be under it, you would do:

"autoload": {
    "psr-4": {
        "": "Classes/"
    }
},

namespace src;

This works if your class is in the src folder. If you added a subfolder of src with your class in it:

namespace src\subfolder;


Answered By - solidforge
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing