Page 1 of 1

beginner Question about including...

Posted: Mon Jul 26, 2010 1:52 pm
by diseman
Hello Experts,

Brand new to PHP and love it, but finding some aspects hard to grasp and/or employ.

Right now, I've got some things working and have one simple question: Can I have some small snippet of code sitting in one .php file and use it in another .php file? I know about:

Code: Select all

<?php include("some_path_here");
but that command seems to pull ONLY the ENTIRE page and insert it. I JUST want a portion of another page's code to be used; not insert the entire page.

Below is the code I want to put into page1.php. What command would I use in page2.php to have it displayed just like it's shown?

Code: Select all

$prop_use_arr['Select'] = "Select";
$prop_use_arr['Primary Residence'] = "Primary Residence";
$prop_use_arr['Second Home'] = "Second Home";
$prop_use_arr['Investment'] = "Investment";
Seems I should be able to assign this code a name and then pull it using that name. The reason is I would actually have quite a few of these (above), but with different array names. I simply wanted to pull them out of page2.php and put them somewhere they wouldn't be accidentally messed with.

Hope that makes sense.

Thanks in advance to anyone who can help...

Re: beginner Question about including...

Posted: Mon Jul 26, 2010 3:40 pm
by califdon
The simplest way is to just store these optional lines of code in separate files, then use include() or require() -- or include_once() or require_once() -- to include the appropriate code when the script is executed.

Re: beginner Question about including...

Posted: Mon Jul 26, 2010 4:47 pm
by diseman
Thanks for the reply. I agree, that would be a simple way, but I have a lot of these to make and that would mean something like 25 extra pages, which seems unnecessary.

Any other suggestions?

Re: beginner Question about including...

Posted: Mon Jul 26, 2010 5:05 pm
by califdon
Remember, these aren't "pages", they are merely scripts. If you only need 3 lines of script, it's just those 3 lines, it's not like a web page document. Having 25 php script files is no big deal. It merely gives you a simple and direct way of getting to the one you want under a specific condition. There may be other, more complicated solutions, such as storing the code in a database, but for only maybe 25 of them, there's nothing wrong with just storing each in a separate file.

Re: beginner Question about including...

Posted: Mon Jul 26, 2010 8:07 pm
by diseman
OK, I will follow your advice although I'm surprised there's no way to just name it and then pull it like we do with a function xxx () for example.

Thank you for your help.