1

I'm starting to learn PHP and OOP and I'm stuck. I have 3 different php files that I paste below. The particular problem is stated after the code:

File1.php :

<?php
class Page{
    public $intro;
    public $article;

}

$TD = new Page($intro, $article); 


$TD->intro="I'm the intro";
$TD->article="I'm an article";
?>

File2.php

<?php
function test($page){
switch($page){
    case "A":
        include "file1.php";
        break;
    case "B":
        include "anotherfile.php";
        break;
    }
}
?>

File3.php (the one that has to print something):

<?php
$page="A";
include "file2.php";

test($page);

echo $TD->intro;
echo $TD->article;
?>

I can't echoing (says that $TD is undefined), but I've been testing and it seems that it's effectively loading the file1.php (where the $TD object is defined). Furthermore, if I paste the problematic echoes in the file1.php and loading this page, the echoes work.

I suppose that it's something obvious but I am not capable of figure it out yet.

Thanks in advance for your response and for reading this to the end!!! :)

Naima
  • 75
  • 1
  • 2
  • 10

1 Answers1

1

Because your include is in the scope of the function, so the variables that are defined in the include are only visible inside of the function.

function test($page){
    switch( $page) {
        case "A":
            include "file1.php";
            // $TD is in scope here, but not outside this scope
        break;
    }
}

A quick fix is to add global $TD; at the top of your test() function.

nickb
  • 59,313
  • 13
  • 108
  • 143