I am new around here and I have a quick question if anyone can help me. To keep it short I am working on a website and I have my files separated by directories and I include the files depending on the name of the page I am on. For example I have a main page dashboard.php that looks something like :
include $file1;
include $file2;
include $file3 etc.
Now I trying to use a class page that include all the files needed automatically when I construct the object.
My problem is when I include the files with the help of the class I can’t seem to find the instance of the object in my included files.
For example : $page=new Page("Test") includes $file1,$file2 etc…. Now when I am trying to use object $page in $file1 it doesn’t fiind it.
If anyone has a solution for this problem or if you think that is a wrong way to design web pages please let me know.
It’s not a problem of includes, the includes are working, I am using autoload and all that the problem is seeing objects methods in classes included through that class. Let me be more explicit :
main.php :
$page=new Page("Test");
Page.class.php :
__construct($title)
{
include($file1);
include($file2);
}
$file1:
echo "test"; // working
$file2:
echo $page->getTitle() // doesn't work, don't worry about the method it exists and works
Per the manual, the
include()function inherits the variable scope of the line it’s included on.I’m assuming you’re currently doing something like:
If you need the file(s) to be accessible outside of the class you want them to be included in, you should add the includes outside of the class, such as:
In the event you need the included files to have access to the class-instance itself (per your latest update), you would use the
$thispseudo-variable. The reason you can’t use$pageinside the included files is because$pagehasn’t been defined; the scope of that variable is inside your main.php file and any other files it includes (but no “inside” classes).You can update your include ($file2) to use
$thiswithecho $this->getTitle()instead ofecho $page->getTitle()and it should work fine.Alternatively, if you would like to use the
$pagevariable instead of$this, you can define it such as$page = $this;right before you include a file that uses it like this: