1

My understanding of including a file in a function was that it stays within that function scope:

If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function.

But when I do this, the second one clashes with the first and tells me the class is already declared!

Run this php page to see the errors (you'll need all three PHP pages)

<?php
class TestOnce
{
    function __construct()
    {
        $this->includeOnce();
    }

    function includeOnce()
    {
        //This should include it once
        include_once "once.php";
        var_dump( $once );
    }

    function includeSomethingThatIncludesOnce()
    {
        include_once "includeonce.php";
        var_dump( $once );
    }
}
$test = new TestOnce();
$test->includeSomethingThatIncludesOnce();
?>

This also inlcudes once, but is told it's already included which it shouldn't be in that function/

<?php
//This should include it once
include "once.php";
var_dump( $once );
?>

This is "once" which declares the class and an instance variable

<?php
class Once
{

}
$once = new Once();
?>

Why aren't the includes restricted to the scope of the function? How would I achieve that?

Don Rhummy
  • 24,730
  • 42
  • 175
  • 330

0 Answers0