Distribute code in files in PHP

In this tutorial, we will read about how to distribute code in different files and how to include code from other files. PHP provides four functions to include code from other files.

  1. include
  2. include_once
  3. require
  4. require_once

include:

Include is used to include external file to current file. It copies all the text from external file and pastes it at the place where it is used. If any error occurs, then this function skip the external file and continue the execution with a warning (without any error).

For example, I have two files: tutorials.php and tutorial2.php in same folder.

tutorial2.php:

  1. <?php
  2. /**
  3. * this is another class in file tutorial2.php
  4. */
  5. class Bird
  6. {
  7. function __construct()
  8. {
  9. echo "class Bird included";
  10. }
  11. }
  12. ?>

tutorials.php:

  1. <?php
  2. include 'tutorial2.php';
  3. // above line is can be written as include('tutorial2.php');
  4. $obj = new Bird();
  5. ?>

Output:

  1. class Bird included

include_once :

It is same as include but the difference is that it includes one file only once. For example, if you have an another file which is including both of the above files using include then class Bird will be included twice. It will create error because one class can not be defined again. In a large project/ application, it happens many times so there is an alternative include_once. It will include tutorial2.php only once and will skip later.

require:

Require is also same as include except it raises internal error (instead of warning) when there is any error during including file.

require_once:

It is also same as include_once except it also raises error like require.

Working with include path:

In above example, both of the files are in same folder and we have called file tutorial2.php directly. It is called relative path. But how will we include file from another folder? We can give a path to file in two ways:

  1. Absolute path
  2. Relative path

Absolute path: This is absolute path of the file starting from root folder. In linux, this will be like this:

include_once( '/var/www/html/findalltogether/tutorial2.php' );

On windows, it will start with drive letter (like C:\www\html\tutorial2.php).

Note that slashes will be opposite for windows.

Relative path: This path is relative to current file (file which is including). Included file can has three relative positions:

  1. In the same folder
  2. In the folder which is in the same folder
  3. In a parent folder or in a folder which is in the parent folder

Lets see all one by one:

  1. We have already used first case. We use direct file name for this type of path.
  2. In second case, we also have to add folder name. For example, if file is in a folder named folder then include('folder/tutorial2.php');. If there are more than more folders then we will navigate to all folders includer('first/second/third/tutorial2.php');
  3. In last case, we will use '../' (two dots and one slash) for backward navigation. Assume our file is /var/www/html/tutorials/include/tutorials.php and we want to include file /var/www/html/another/tutorial2.php then we will use include(../../another/tutorial2.php). '../' means back to one folder.

Namespaces:

{key points: namespace, sub namespace, use}

In large projects, it is possible (generally happens) that we have two functions/ classes with same name and in different libraries or files. Sometimes we have to include both files in a single file. It raises error because we can not define a funciton/ class more than one time. So, namespaces help in avoiding clashes. Namespaces are like folders. As we can not place two files with same name in a folder similarly we can not define two functions/ classes with same name in same namespace but we can do in different namespace.

For example, we are making a shopping system. we have two display methods one in cart.php for displaying cart and other is in checkout.php for displaying checkout information. We want to include these functions in a file which is deciding if user has presses checkout or not and if user has presses checkout then call display() function from checkout.php otherwise call display() function from cart.php. We will use namespace here. As we can define functions with same name in different namespace, we will not get any error.

checkout.php

  1. <?php
  2. namespace Checkout;
  3. function display()
  4. {
  5. // code for display function
  6. echo "dispay in checkout";
  7. }
  8. ?>

cart.php

  1. <?php
  2. namespace Cart;
  3. function display()
  4. {
  5. //code of dispay function in cart
  6. echo "display in cart";
  7. }
  8. ?>

tutorials.php

  1. <?php
  2. // including files in different namespace
  3. require 'checkout.php';
  4. require 'cart.php';
  5. // checking condition
  6. if ( $action == "checkout" ) {
  7. // calling from checkout namespace
  8. Checkout\display();
  9. } else {
  10. // calling from cart namespace
  11. Cart\display();
  12. }
  13. ?>

Note the following points:

  • Namespace is create by writing namespace Namespace_name; just after <?php.
  • We can write more than one namespace in a single file, but it is not a good programming practice. We should avoid it.
  • We call functions and class from namespace by Namespace_name\ function_name() and Namespace_name\ class_name() respectively.

Sub-namespaces and Use keyword:

We can define sub-namespace just like sub folder. Syntax is => namespace Namespace_name/sub_namespace_name/another_sub_namespace; Using sub-namespace is same as namespace. For large project name of sub namespaces become very long. It is very irritated to write whole name again and again. So php provides use keyword for this. Use keyword assign whole name to a single word name.

Syntax is => use long_namespace_name as short_name;

After it we write short name of namespace instead of writing whole name. This short name is called alias.

  1. <?php
  2. require "checkout.php";
  3. // here is long name of namespace is assinging to short name
  4. use Namespace\SubNamespace\FrontEnd\Checkout as NewCheckout;
  5. NewCheckout\display();
  6. ? >

NOTE: We can remove as keyword and alias. If you will remove then then by default, last word (Checkout in last example) will be the short name of the namespace.



About Harish Kumar

Harish is an interested person in the field of web development and blogging. He works for the need of young web developers in learning various languages, latest technologies and other essential tips and tricks. If you need some help or you have some suggestion then you email him at harish@findalltogether.com without any hesitation. You can also suggest/demand for articles of your own choice.

Related Articles

In this part of free tutorial series, I am telling you about syntax, variables, data types, comments, constants and o...
Introduction to PHP
In this part of free step by step tutorial series I will teach you about for loop, while loop and do while loop of PH...
loops in PHP
In this part of free step by step tutorial series I will teach you about if, if else, nested and switch statements of...
Conditional statements in php

Login or Sign up to leave comment.