Including file Inside class

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
blasterstudios
Forum Newbie
Posts: 13
Joined: Thu Dec 23, 2004 10:08 am
Location: Alabaster, AL
Contact:

Including file Inside class

Post by blasterstudios »

I'm trying to write a class that has the option of including a file or including plain HTML. I'm not sure how to execute this properly. I was reading up on how to do this, and it seems the suggestion is to "return a value" at the end of all include files. Is there a way to avoid this? I tried using their fuction get_include_contents, however it seems like my variables are not working. If I have

mypage.php
- include file1.php - set $var = "asdf";
- include file2.php (within my class) - echo $var;

it does not show anything.

I want my include files to work just like standard include files. How can I get this to work?
blasterstudios
Forum Newbie
Posts: 13
Joined: Thu Dec 23, 2004 10:08 am
Location: Alabaster, AL
Contact:

Re: Including file Inside class

Post by blasterstudios »

Ok, I'm assuming that my issue is because my setup is;

my_class {
my_function(){
include("my_include.php");
}
}

And it has something to do with variable scope as mentioned here http://answers.yahoo.com/question/index ... 636AAUsG1K

So, I guess my question is, what can I do inside my function to make my includes work like they are part of the page, OR how should I include a dynamic file in my class so that it functions normally.

Thanks.
koen.h
Forum Contributor
Posts: 268
Joined: Sat May 03, 2008 8:43 am

Re: Including file Inside class

Post by koen.h »

If I understand the problem correctly, it's indeed a scope problem. But it's difficult to say how to solve it as we don't know how you assign your values.

An option is something like this:

Code: Select all

 
class MyClass
{
    private $data = array()
 
    function prepareVariables
    {
        $this->data['title'] = 'My Personal Blog';
    }
    function loadFile()
    {
         // include file
    }
}
 
Then in your file:

Code: Select all

 
<html>
// more html etc
<h1><?php $this->data['title']</h1>
// more html
</html>
 
Post Reply