0

I've been told I have to create a config.php file that will hold all of the classes.

For example let's say I have 3 classes.

Class 1: House

Class 2: myCar

Class 3: Road

And in config.php I call them:

$house = new house();

$mycar = new myCar();

$road = new Road();

and then I include that config.php file in every page, for example index.php.

But now, I want to extend class Road.

I can't include config.php in that class? Or include the other' class file in it while it is already included in config.php.

Is this the wrong way of setup for classes?

How can I extend classes without having errors.

Do I have to create a new object everytime?

Example:

Instead of including a config.php Ill do this:

/**
 * Index.php
 **/
include("class/house.class.php");

$class = new House();

echo $class->echoMe("hey");

And in every file I will do the same, by creating new objects, so then I can extend some specific classes when needed?

2 Answers 2

2
function autoload($class) {
    if (is_file($file = 'www/content/includes/class/'.$class.'.php')) {
        require_once($file);
    }
}

spl_autoload_register('autoload');

Include the following code in your config.php file. Make sure that you include the config file in every file where you want to load your classes.

Make sure that the file has the same name as the class your calling. For an example

$house = new House();

would require the class filename to be House.php

Start each class file with

<?
    class House {

        function something() {

        }

    }
Sign up to request clarification or add additional context in comments.

3 Comments

Lets say I want to handle login, and login is located in users.class.php. Can I include users.class.php in login.php and do $users = new Users();? Is that a proper way?
Thanks a lot, I see now.. So now I only have to include the config in login.php and simply do $users = new Users(); ?
Yes. Just make sure that the path to the class folder is correct and that the php file is called Users.php and you should be fine :)
1

You could use spl_autoload_register() Basically you create a function that is called every time a class that PHP hasn't come across before is called.

/**
* config.php
*/
function classAutoLoad($class) {
    if (file_exists("class/$class.class.php"))
        include("class/$class.class.php");
}

spl_autoload_register('classAutoload');

/**
* someFile.php
*/
reauire_once('config.php');
$house = new House();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.