Search code examples
phpoopincludeinclude-path

Include_once in Object dont work


I got a problem with php and OOP.
I tried to create a object and inside the object I tried to load data from mysql.

My files are build like this.
HTML
|_ php
|__ objects
|_ content

In object folder is the object file "Event". The object created in a script in php folder and the whole script is called from a html file in content.

My Problem is, that i use the object from different locations. And the include_once method wont work.

event.php:

<?php
include_once(ROOT.'php/db.inc.php');

class Pb1_event
{
    public $ev1_id;
    // do something
}

I also tried it with include_once('./../db.inc.php');. How should I include it ? Is it a good way to include it in this file or should I include it anywhere else ?


Solution

  • Firstly what I would do is use either __DIR__, or better is $_SERVER['DOCUMENT_ROOT'] for absolute pathing. These are constants that will refer to your server web root. Assuming it refers to the root directory you have given to us, you would do:

    require_once $_SERVER['DOCUMENT_ROOT'] . '/php/db.inc.php';

    But to gain a better understanding, you should echo it and see how your directory paths. Also, for the "best practices" you should use autoloading, you can read more about it here:

    http://php.net/manual/en/language.oop5.autoload.php

    Define an autoload function and have it call the file you need, for example, if you need a class called DB your function might look something like this:

    function __autoload($class) {
        if ($class == 'DB') {
            require_once $_SERVER['DOCUMENT_ROOT'] . '/php/db.inc.php';
        }
    }