Wednesday 2 June 2021

Php: include_once, require_once

require_once

The require_once expression is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.

 

include_once

The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns true. As the name suggests, the file will be included just once.

 

Why to use require_once, include_once statements?

If the same file is included more than once during the execution of particular php file, it leads to.

a.   Function redefinitions

b.   Variable value reassignments etc.,

 

Let’s see it with an example.

 

a.php

<?php
    $my_org_name = 'ABC Corp'
?>

 

b.php

#!/usr/bin/php

<?php
    include 'a.php';

    echo "my_org_name : $my_org_name\n";

    echo "\nSetting my_org_name to XYZ Corp\n";
    $my_org_name = 'XYZ Corp';

    echo "Reincluding the file a.php\n";
    include 'a.php';

    echo "my_org_name : $my_org_name\n";

?>

 

Output

$./b.php 


my_org_name : ABC Corp

Setting my_org_name to XYZ Corp
Reincluding the file a.php

my_org_name : ABC Corp

 

As you see b.php application, I set the value of ‘my_org_name’ to ‘XYZ Corp’ and re included the file a.php. Since a.php has assigned the value of of ‘my_org_name’ to ‘ABC Corp’, whatever the changes we have done in a.php are reassigned. In case of functions, they will be redefined, to avoid these problems, use include_once or require_once.

 

Let’s update include statement with include_once statement in b.php file and rerun the application.

 

b.php

 

#!/usr/bin/php

<?php
    include 'a.php';

    echo "my_org_name : $my_org_name\n";

    echo "\nSetting my_org_name to XYZ Corp\n";
    $my_org_name = 'XYZ Corp';

    echo "Reincluding the file a.php\n";
    //include 'a.php';
    include_once 'a.php';

    echo "my_org_name : $my_org_name\n";

?>

 

Output

$./b.php 


my_org_name : ABC Corp

Setting my_org_name to XYZ Corp
Reincluding the file a.php
my_org_name : XYZ Corp

 

 

 

 

 

 

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment