views:

100

answers:

2

I have a large function that I wish to load only when it is needed. So I assume using include is the way to go. But I need several support functions as well -only used in go_do_it().

If they are in the included file I get a redeclare error. See example A

If I place the support functions in an include_once it works fine, see Example B.

If I use include_once for the func_1 code, the second call fails.

I am confused as to why include_once causes the function to fail on the second call, it seems to not 'see' the code the second time but if nested functions are present, it does 'see' them.

Example A:

<?php
/*  main.php    */
go_do_it();
go_do_it();
function go_do_it(){
    include 'func_1.php';
}
?>

<?php
/*  func_1.php  */
echo '<br>Doing it';
nested_func()

function nested_func(){
    echo ' in nest';
}
?>

Example B:

<?php
/*  main.php    */
go_do_it();
go_do_it();
function go_do_it(){
    include_once 'func_2.php';
    include 'func_1.php';
}
?>

<?php
/*  func_1.php  */
echo '<br> - doing it';
nested_func();
?>

<?php
/*  func_2.php  */
function nested_func(){
    echo ' in nest';
}
?>
+1  A: 
cletus
+4  A: 

I have a large function that I wish to load only when it is needed. So I assume using include is the way to go.

Your base assumption is wrong. This kind of optimization is counter-productive; even if your function is hundreds of lines long there will be no noticeable benefit to hiding it from PHP's parser. The cost for PHP to parse a file is negligent; real noticeable speed gains come from finding better algorithms or from better ways to talk to your database.

That said, you should be including the function definition in the included file. Rather than moving the body of the function into func_1.php, move the entire function into the file. You can than require_once the file containing the function inside each file where you need it, and be sure that it is included exactly once regardless of how many times you attempt to include it.

An example:

#file1.php
function test() {

}

# index.php
require_once('file1.php');

include('table_of_contents.php');
test();
meagar
The function is almost 1000 lines and is called from my session.php, so every ajax request would be loading useless code, except the few times it is used. Should I still load it as per your first paragraph?
Mahks
If you've got a 1000 line function, that is your problem. No function should ever, *ever* be 1000 lines long.
meagar
So how do I execute the code from several locations?
Mahks
I originally just included the code as needed, but then I had issues when it was needed in several places, and ran into the redeclare problem with the support functions.
Mahks