Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use require_once inside function [duplicate]

Tags:

php

mysql

Hello i want to use require_once inside a function but not working??? actually i have three functions in my page how can i do that.... its working out side but not inside functions ???

Any one please ????

here is my code:

 <?php
    //**************************************
    //     Page load dropdown results     //
    //**************************************
    function getTierOne()
    {
        require_once('../config.php');
        $provincequery="SELECT provinces.ProvinceID, provinces.ProvinceName FROM provinces WHERE ProvinceID > 0";
$result=$coon->query($provincequery); // mysqli neeeds connection while running the query
          while($province = mysql_fetch_array($result)) 
            {
               echo '<option value="'.$province['ProvinceID'].'">'.$province['ProvinceName'].'</option>';
            }

    }
like image 739
user2279037 Avatar asked Oct 05 '22 05:10

user2279037


1 Answers

Actually, form a technical point of view, you can use require_once() inside a function. However it is most likely a bad idea and not what you really want to do:

  • including code inside a function literally includes the code there. This means that all included code is evaluated inside the scope of the function. PHP declares all functions global, but variables and plain code sequences are bound locally, so not visible outside the function executed right now.

  • since you use a relative path to load the included file you are limited to execute your function from within a certain file system level. This limits how your code can be used...

Whilst this might actually be what you want when the included file holds some local configuration you will almost certainly stumble over this:

  • require_once() requires only once, this is what the function is there for. This means: if you enter your function getTierOne() more than a single time then for every subsequent run the require_once() simply won't include any code, since it already has in the first run. So wether you get your configuration included or not depends! That is a horrible design!

So either include your configuration globally and for example store it inside some variable which you can then refer to inside your function or you use require() or include() to make sure the configuration really is included in every execution of the function.

like image 150
arkascha Avatar answered Oct 18 '22 03:10

arkascha