Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does OOP manage to 'include' classes stored in different files [closed]

I'm trying to move into OOP development and am turning to here as I'm sick of searching the web and finding only the very basic information about what classes are and how they can inherit from each other - that I understand.

What I don't understand as yet is how all these classes can be stored in different files, doted around a folder structure, and yet all you need to do to use the class is just mention its name in your code. How does this work exactly?

And on a related note, if anyone can recommend a good book or online tutorial which will provide a good foundation in OOP (preferably php based) I'd be very grateful.

like image 225
wheresrhys Avatar asked Apr 22 '09 20:04

wheresrhys


2 Answers

PHP has functionality to automatically load files based on some call you make. PHP: Autoloading Objects is your definitive resources on the matter.

like image 184
Anthony Avatar answered Oct 23 '22 18:10

Anthony


The technology answer is PHP Autoloading.

The implementation answer is this:

One common method used has to do with the names of classes relating to folder structure. There are articles out there, but here is a brief summary:

When setting up your autoload code, take the class name and replace underscores with slashes. This way you can organize your classes in folders.

For example:

Classname: Database_Provider_MySQL

File: Database/Provider/MySQL.php

So in autoload, you'd take the incoming classname, replace the underscores with slashes. Then include that specific file.

This achieves what you are trying to accomplish, you can simply load a class by creating a new instance of it. You never have to use the include statement for these classes.

Do remember to not go to deep where you end up with 6+ levels. I think between 3 and 5 is a good maximum.

Also, this does require that you keep only 1 class per file (similar to Java). Though it might seem inconvenient, it makes locating code a lot easier.

like image 44
Jordy Boom Avatar answered Oct 23 '22 18:10

Jordy Boom