views:

63

answers:

4

According to the PHP manual $a should be available to b.inc in the following code segment:

<?php
$a = 1;
include 'b.inc';
?>

However when I try to do the same when calling a static method, $a seems to be out of scope.

class foo {
    public static function bar() {
        $a = 1;
        include('b.inc');               
    }
}

foo::bar();

Am I misunderstanding something? EDIT: Okay, I'm an idiot, everybody. I was using a wrapper function for the include -- to fill in the include path. This took the variable out of scope. Thanks for the help.

A: 

Inside the class you need to say that you mean the global one.


class foo {
    public static function bar() {
        global $a;
        var_dump($a);
    }
}

foo::bar();
racetrack
You misunderstood his question. He's saying that when he includes it in a static function, the file does not seem to see $a.
hopeseekr
+1  A: 

It totally works for me. If you are describing the problem accurately, something must be happening to $a inside of b.inc.

hopeseekr
Thank you -- I must have screwed up somewhere. Apologies.
Greg
For the record, you are using php 5.2.14, right?
hopeseekr
Yes. I also have my include in a foreach loop -- but I don't see how that would make any difference. I'll post my error when as soon as I figure it out.
Greg
Man! No offense, Greg, but I seriously question your PHP proficiency if you are including a file in a loop.
hopeseekr
It's just an HTML template to avoid putting a bunch of markup into the helper function. Is there a serious problem with this?
Greg
Okay -- even though this might not see a whole lot of iterations, I suppose that is more than just a little herp derp on my part. The loop is in the template itself template now.
Greg
Awesome, that's by far a better place for the loop. Just as Rasmus about looping inclusions. He *rails* against them in his PHP talks.
hopeseekr
A: 
<?php
//a.php
class test
{
    public static function run()
    {
        $a = 'Some value';
        include 'b.php'; //echo $a;
    }
}
test::run();
?>

all works fine in my test aswell.

RobertPitt
A: 

Function scope is different than the global scope. b.inc will see $a, and any variables created in b.inc will be in foo::bar()'s scope (unless they are defined as globals, or inside their own function scope).

You can test this with some code:

function foo() {
    $a = 1;
    include '1.php'; // modify and initialize, ie. $a++; $b = 3; 
    include '2.php'; // test the values: $a == 2; $b == 3
}

We run into this problem occasionally when we bootstrap WordPress in other scripts: the initialization scripts assume they are in the outermost scope so they will set variables like $wpdb (the database object), but that file will actually get created in some function that did a require_once(). The solution is to always bootstrap WordPress in the app before you get into any function scope.

Adam Backstrom