Where is it wisest to include files in a PHP class file? For example if one of the methods needs a external class, should I include the file where it is used in that method, or should it be done before the class? Or in the constructor? Or? What do you recommend? Pros? Cons? Or is it just a matter of taste really?
include_once 'bar.class.php';
class Foo
{
public static function DoIt()
{
new Bar();
}
}
vs
class Foo
{
public static function DoIt()
{
include_once 'bar.class.php';
new Bar();
}
}
I prefer it on top, the same convention as for #import/import/using in c/java/c# as it immediately lets you know what other classes your class is depending on.
You may also want to check out require_once() instead of include_once() as it will halt with an error instead of giving a warning when the included file contains an error. But of course that depends on what kind of file you're including and how critical you deem it to be.
I would say that it depends.
So, if there is a rather large code base, and you would prefer to keep the code loaded into memory each time there is a page request down to a minimum, then I would suggest only including the other php file when needed.
However, if that script is always needed, then include it at the top of the script.
It really comes down to the situation and requirements.
Hope that helps.
It depends on architecture you are using. Including files in the beginning is neat, but if that file prints text then you wont be able to manipulate headers etc.
When you are using MVC pattern controller should include class files.
If you're sure you need the file included, do it at the top. If you need files included on demand, you might want to look into spl_autoload_register() to ease the pain.
It is always good to include external files on top of the page. It will be very easy to locate later. If the included file is very large then include it wherever you need. See also the documentation for require_once and include_once.
There's also simply require and include. Know the difference between them and which to use when.
Related
I'm new to PHP, so for example if I have a parent file that include the 2 child files:
include_once('includes/child1.php');
include_once('includes/child2.php');
If child2.php have a class Test with a function test_function:
class Test
{
static function test_function() {
}
}
then can we access this test_function in child1.php like this?
public static function initialize() {
Test::test_function()
}
and if it can, why does it not produce an error since child1.php is included before child2.php(note: I'm coming from Javascript perspective)
No code in child1 or child2 is actually being called. You're just defining some classes and functions, but nothing is calling any of these functions. Test::test_function() is never ever being evaluated, hence it cannot throw any error.
In general: yes, order matters. Everything you're trying to call needs to be defined before you call it. In this case, you're not calling anything, hence it's irrelevant.
Each file should take care of its own dependencies. I.e., child1.php should include (or better: require) child2.php itself if its code depends on it. Don't put the burden of including dependencies on the eventual user of child1.php, this just makes things extremely complicated.
In fact, you should be using autoloading, which will include all necessary files just in time as needed without you having to worry about the complexities of multiple include statements.
You can think of the include family ( include_once, require, require_once ) as a cut and paste type operation. If you follow just envision php creating one big file, pasting the content from each include call ( in the top down order of execution ).
So you might have
index.php
includes.php
functions.php
And if you do this in index
include 'includes.php'
some_function();
And then in includes.php
include 'functions.php'
And then in functions php you have a function some_function(){} you can use this in the index file after the include, php will see it like this
include 'includes.php'
include 'functions.php'
some_function(){}
some_function();
In your example above you would not be able to call the class because you are calling it before including it. Like this
//include_once('includes/child1.php');
Test::test_function();
//include_once('includes/child2.php');
class Test
{
static function test_function() {
}
}
However that said I notice you defined a "method" around your call to Test::test_function() that method would need to be wrapped in a class to work, if that was the intended way then it depends when you instantiate that class, you must do that after the Test class is defined. So for that case we will assume that that method is in a class
class Test2{
public static function initialize() {
Test::test_function()
}
}
Now if you use this class back inside of the parent file or anywhere after the include of child2.php then it will work, so in the parent file if you do this.
include_once('includes/child1.php');
include_once('includes/child2.php');
Test2::initialize();
You would think of this as a big file like this
class Test2{
public static function initialize() {
Test::test_function()
}
}
class Test
{
static function test_function() {
}
}
Test2::initialize();
It should be fine. You just cant call it before it is defined. Make sense?
All that said, I would strongly suggest looking into a PSR autoloader, that is the standard way of including classes these days.
Here is a good post on the topic
http://www.sitepoint.com/autoloading-and-the-psr-0-standard/
Update explination
I'll try to make this as simple as I can. The way PHP works is it loads a file and parses the code, this basically means it just checks the formatting for syntax errors or typos and any new functions or class definitions ( it only registers the names of that new stuff and checks the syntax ). Once that is done and passes it starts to execute the code from top to bottom.
Now when including a file it can't parse it right away because it needs to execute the includes, which it does not do during the initial parsing. After it runs the include it parses the new chunk of code, and then continues executing that new code from top to bottom until the end of the included file at which point it returns to the original file and continues on from the include deceleration.
So while it seems different that you can run a function before defining it in the same file, but not in an included file, it is actually the same behavior. This is because it needs to execute the file to know the functions or code that is in it. So if you call the function before the include, PHP hasn't had a chance to even look in the file yet. Some of this is because you could put an include in an if statement and then PHP would not need to include the file.
What it doesn't do is, parse the file run all the includes and then run the code. I hope that clarified how the process flow works.
Having functions that are quite big and they are loading every time the page is loaded, would be better to write function foo(){ include(.../file_with_function's_code); return; } to minimize the size of the functions script? Or it doesn't matter because when a function is loaded (but not executed) also is loaded the content even if it is into an include? Thank you.
(Edit: my question is not about if it's possible or not)
While #Luceos answer is technically correct (the best kind of correct), it does not answer the question you asked, namely is doing this better, or do includes happen regardless of function calls?
I tested this in the most basic way (OP, why didn't you?):
<?php
echo "Testing...";
function doThing() {
include nonExistantFile.php;
}
//doThing();
echo "Done testing.";
Results:
if I call doThing(); I get a file not found warning.
If I comment out doThing();... there is no error! So you can save file load time by doing this.
Or, as a good alternative, encapsulate your functions in classes, and take the benefit of __autoload :
function __autoload($class_name) {
include $class_name . '.php';
}
Encapsulate myBigFunction() in a class
class myBigFunction {
public static function run() {
//the old code goes here
}
}
save it as myBigFunction.php
When you call the function as static method on the class :
myBigFunction::run()
__autoload will load the file, but not before that.
Yes that's possible; see http://www.php.net/manual/en/function.include.php
If the include occurs inside a function within the calling file, then
all of the code contained in the called file will behave as though it
had been defined inside that function. So, it will follow the variable
scope of that function.
Question is, why not add the surrounding function definition to that included file. I think the only viable reason to include within a function is to split code within that function into bits.
Both Luceos' and Albatrosz could be misread, so I felt that I should clarify these.
The include set of directives generate a runtime ZEND_INCLUDE_OR_EVAL operation which calls the Zend compiler to compile the referenced file. So in general you should not embed include statements in a function, as:
The include will be executed every time that code path is taken when the function is called. Compiling the same bit of code 100s of times is a bad idea.
If the code contains elements of global scope (e.g. function or class declarations) then executing that declaration even twice will cause compiler errors.
So don't unless you know what you are doing. Use techniques such are those described by Albatrosz. Incidentally his __autoload() function is just the sort of example of an exception where this is valid to do.
I read about the class autoloading in PHP, but till now I didn't understand why we should use __autoload() method?
I read that
PHP doesn't use
this method becuase it has the handy little include functions,
include_once and require_once, that prevent you from loading the same
file more than once, but unlike a compiled language, PHP re-evaluates
these expressions over and over during the evaluation period each time
a file containing one or more of these expressions is loaded into the
runtime in this site why we should use autoloading,
but I don't understand what is the meaning of PHP re-evaluates in the above statement!!
why require-once don't solve the problem of loading php file more than once?
The original article is more clear when you read it more widely (see below) :
It simply says that __autoload() is smarter than include_once() because the function include_once() has to be coded explicitly when the class may be required, and also because this function needs to be processed each time it appears in order to know if the file given in argument is already loaded or not.
The other function __autoload(), on the contrary, can be called only once for several classes you may need. And then PHP tryes to load the corresponding source file only when a class definition is missing.
We can sum up this argumentation by saying: you need one include_once() for each Class/Function source, while only one __autoload() may be enough for a set of Class source having the same location rule.
Snippet of the article:
Why you should use an autoload function in PHP
The loading of classes is something that managed languages like Java
and C# don't need to worry about, class loaders are built into the
compiler.
[...]
PHP doesn't use this method becuase it has the handy little include functions, include_once and require_once, that prevent you
from loading the same file more than once, but unlike a compiled
language, PHP re-evaluates these expressions over and over during the
evaluation period each time a file containing one or more of these
expressions is loaded into the runtime. That is where the Standard PHP
Library (SPL), introduced in PHP 5, and the wonderful little _autoload
function come in to enhance the speed and uniformity of your PHP code.
__autoload is a magic function, that you define, that enables PHP to let you know when it doesn't have a class loaded, but that class
needs to be loaded.
The include_once statement itself is reevaluated whenever encountered.
for ($i = 0; $i < 100; $i++) {
include_once 'foo.php';
new Foo;
}
This will evaluate ("run") the include_once 100 times. That can be something of a slowdown. On the other hand:
for ($i = 0; $i < 100; $i++) {
new Foo;
}
When using autoloading, the logic for file inclusion will only be triggered once, the first time the class is needed.
but till now I didn't understand why we should use it
When you have structured and organized your work, because of the organization it results that you have many similar class files. The simpler example is an mvc, but not only, any custom structure will result in similar files containing a class, then because of the similarity you put them in the same folder and also you use a common file naming convention for example you can have a controller and a model directory.. check example file: employeeModel.php, statisticsModel.php, indexController.php, errorController.php
Well you can take advantage of this fact, check this customized autoload function:
/*** function to include model and view classes ***/
function __autoload($class_name)
{if(__DEBUG) eval(__DEBUG_EVAL);
/*** Load a model class ***/
$mfile=__SITE_PATH .'model/'.$class_name.'.php';//echo 'model file'.NL;v($file);
if (file_exists($mfile)){
include ($mfile);
if(__DEBUG) //store debug info before include
eval('error_log("autoload Success file exists: ".$mfile.NL);');
return true;
}
/*** Load a view class ***/
$cfile=__SITE_PATH .'view/'.'/'.substr($class_name,0,-4).'/'.$class_name.'.php';//v($file);
if (file_exists($cfile)){
include ($cfile);
if(__DEBUG) //store debug info before include
eval('error_log("autoload Success file exists: ".$cfile.NL);');
return true;
}
return false;
}
It also has a few lines for debugging that can easily be removed later. Because of similarity in things it can decide it self what to include and also to report errors when occur. Without this autoload function you would have to care that class files are availoable before use. Also this function will allow to include a file once, if you check carefully it does not use include_once, this means that autoload fires only when the file has not been seen before, in contrary to simple file inclusion which is fired every time the code is executed as very correctly decese notice it.
Conclusion Autload = fires once per file, automates things, so you execute a class directly without caring to include it.
Autoloading means if you need some classes to be included automatically in the scripts like
require_once ("class.user.php");
require_once ("class.module.php");
To avoid such code for each script you can use Autoloading functionality of php
This question already has answers here:
PHP include best practices question
(10 answers)
Closed 9 years ago.
What is the best practice for including PHP files?
Is it best to include a include.php file that includes all of the project PHP files?
Or to include it in those files that need them
Right now, my project has several include files in my index.php file. Does including all of my php files in the index.php make it less efficient?
Lastly, Where should one include the session check PHP file? in all of the PHP files?
EDIT 2016
Well, 5 years since I replied this. I am still alive. A lot has changed.
Now I use autoloaders to include my files. Here is official info for autoloaders with examples.
Basically, the idea is to have a proper folder structure (PSR-4 standards for instance) and having a class within each file. This way you can use autoloaders and PHP will load your files automatically.
OLD ANSWER
Usually, I have a config file like this:
define(root, $_SERVER['DOCUMENT_ROOT']);
.... // other variables that are used a lot
include (root . '/class/database.php');
.... // other includes that are mostly called from each file, like a db class, or user class, functions etc etc...
if (defined('development'))
{
// turn error reporting on
}
else
{
// turn it off
}
etc etc... You got the point of config.
And I include the config.php on each file. I forgot how to do it right now, but apache can do the automatic include for you. Therefore, you can say to apache to include your config file by default.
Then, I have controller classes, which call the views. There in each function I call the view.
someController.php
function index() { include root . '/views/view_index.php'; }
finally, from the view, if I need to include the header and footer view I do it like this:
view_index.php
<?include root . '/view/shared/header.php';?>
<div class="bla bla bla">bla bla bla</div>
<?include root . '/view/shared/footer.php';?>
I always use include in this structure rather than include_once since the latter requires extra check. I mean, since I am pretty sure that I include files only once, I don't need to use include_once. This way, you also know which include is where. For instance, you know that crucial files like db.php, or functions.php are located in config.php. Or you know that include views are located in controllers. That's pretty useful for me, I hope that helps you, too.
Using the include.php file is a very good practice according to me, as it is very helpful in changing the included files in big projects. If the project is small then including individual files is not a problem. But it becomes a problem to manage them as the project grows big.
For the session check file it is better to attach them individually as the requirement to check session on different pages might differ.
Including files individually or including them all in a single file and then including that makes much of the difference to the performance. As ultimately all the files are going to be included. It only becomes easy to manage them if single file is used to handle them.
I don't assume you are using object oriented programming but in case you do here might be a good answer.
In php you can define a function called the autoloader, if you try to create an object of a class that has not been defined the autoloader is called. You can then use the class name to figure out where the file containing that class is stored to include it at the last moment. Here is an example..
<?php
function on_load($class)
{
if(file_exists(require_once('classes/'.$class.'.php')))
{
require_once('classes/'.$class.'.php');
}
else
{
throw new Exception('Class not found: '.$class.' in classes/');
}
}
spl_autoload_register('on_load'); // tell php to call your on_load function if the class was not defined
If you're working on a big project you might want to group your files like this
/classes/database/MySQL.php
/classes/database/PDO.php // I'm just listing random stuff
/classes/Core.php // Whatever
/classes/datastructure/HashMap.php
You can then use a special naming convention to find the right directory
class Database_MySQL{} // look in <root_dir>/database/ for MySQL.php
class Core // look in <root_dir>/ for Core.php
class Database_Driver_Adapter_Useless_MysqlAdapterThingy {} // look in <root_dir>/Database/Driver/... blabla
Or you can use the php 5.3 way and define your classes like this
<?php
namespace database\driver\adapter\useless;
use database\driver\adapter\MysqlAdapter; // Now you have to tell PHP which version of MysqlAdapter class you want to use, even if there is just one
class MysqlAdapterThingy extends MysqlAdapter {}
Now you have to use the 'use' keyword in every file you need that class. The cool thing is that the namespace is automatically added to the class-name for your autoload function so you can do something like this
function on_load($class)
{ require_once('root/' . str_replace('\\', '/' $class)); }
If you want to learn more try googeling PHP auto-loading there is tons of information on this subject. But then again. From the format of you question I do not assume you're using OOP so this answer is just for the people who found this question on google.
Edit
I would also like to add the following:
// Only include the file once even if you place this statement multiple times
require_once('bla.php');
include_once('bla.php');
require('bla.php'); // Error if file doesn't exist, php will not continue
inlcude('bla.php'); // Warning if file doesn't exist, but php will continue
Using include or require without _once means that file will get included every time the statement is executed
Use include for template or user generated files, use require_once for classes
Just think easy, and think about load as less as possible and don't include something unnecessary.
So for your PHP files. if you include same php files on different pages just create 1 PHP file with this files in it.
If you use a PHP file in 1 page or 2 only, just include them seperate.
I hope i helped you with it ;)
Include files independently, use require_once() function instead of include, as require_once allow only one inclusion of file...
like
require "class.a.php";
require "class.b.php";
require "class.c.php";
class main{
function main(){
if(condition_is_met(){
$this->something = new A();
}else{
$this->something = new B();
}
}
}
Should the files be included in the condition check with require_once, and not all the time?
The question is not clear. In the current code, I think all of the file(s) will get included, whether you use (declare variable of these classes) them or not. If you wan't to not load the class(es) you will not use, you can use the __autoload() function.
http://php.net/manual/en/language.oop5.autoload.php
PHP has to open the file and parse it so it has some impact. For a few files I wouldn't worry about it but it can get out of hand as your files increase. That's why there's autoload, which allows you to load class files only when needed, without having a long list of requires at the top of your files:
http://php.net/manual/en/language.oop5.autoload.php
Also take a look at spl_autoload_register:
http://www.php.net/manual/en/function.spl-autoload-register.php
The only performance it should effect is the time to parse it, but I think that is preferred over complicated include logic hidden midway inside of your file. Not to mention that if you put the require inside of the if statement it is like you inserted that file's text inside of that if statement, which isn't right (and may not work).
Can anyone tell me if you can declare a class inside of a function/if statement?
Anytime you use include or require, PHP is basically copy/pasting the code from the required file into your code. So no matter where you put it, PHP is still opening the file, reading it and dropping it in there, it won't be affected by an if block. In other words, require is parsed before the code is actually run, so yes, you will take a (very small) performance hit even if require is put in an if block and never run. Keep in mind, this is a very small impact. Lastly if you are worried about it, I would use require_once - this ensures that this parsing does not happen twice, for example if a second required file requires the first file, this redundancy won't amount to a second performance hit.