Monday 31 May 2021

Php: Organizing your code

In a typical application, source code is logically organized into multiple files. For example, all the utility classes can be located at ‘utils’ folder and all the entity classes are in ‘entities’ folder etc.,

 

How to include the code from another file to this file?

There are two ways to include code from one file to other.

a.   Using include statement

b.   Using require statement

 

include statement

Syntax

include 'file_name.php';

 

require statement

Syntax

require 'file_name.php';

 

include vs require

In case of include statement, if a file is not exist, compiler throw a warning (do not terminate the application). But in case of require directive, if the file is not exist, then compiler throws an error and you can’t run the program.

 

Let’s try to understand this with an example.



Let’s create a root folder with following content.

a.   Create utils folder and place arithmetic.php file under utils folder.

b.   Create main.php file under root folder.

 

You can access the content of arithmetic.php file from main.php using following statement.

include 'utils/arithmetic.php';

 

Find the below working application.

 

arithmetic.php

<?php
    class Arithmetic{
        public function sum($a, $b){
            return $a + $b;
        }
    }
?>


main.php

#!/usr/bin/php

<?php
    include 'utils/arithmetic.php';

    $arth = new Arithmetic();

    $sum_10_20 = $arth -> sum(10, 20);

    echo "sum of 10 and 20 is $sum_10_20"
?>


Output

$./main.php 

sum of 10 and 20 is 30


You can even include a php file within the scope of a function.

 

Example

function inc_by_10($a){
    include 'utils/arithmetic.php';

    $arth = new Arithmetic();

    return $arth -> sum($a, 10);
}


In the above example, contents of the file arithmetic.php are available within function scope, not accessible outside the function.

 

Find the below working application.

 

include_file_within_function_scope.php

#!/usr/bin/php

<?php

    function inc_by_10($a){
        include 'utils/arithmetic.php';

        $arth = new Arithmetic();

        return $arth -> sum($a, 10);
    }
    
    $a = 20;
    $a_plus_10 = inc_by_10($a);

    echo "a : $a\n";
    echo "a_plus_10 : $a_plus_10\n";
?>

Output

$./include_file_within_function_scope.php 

a : 20
a_plus_10 : 30

Note
In php all the files are included in one server request, but it is not the case with html.




Previous                                                    Next                                                    Home

No comments:

Post a Comment