i have just learned about include() function in php, which enables to include whole document into another document. i was wondering how to do the same, if i would like to include not a whole document, but only a snippet of code, from one document into another one.
-
4why dont you put that snippet in an extra file?timbmg– timbmg2015-02-04 07:13:14 +00:00Commented Feb 4, 2015 at 7:13
-
i just wonder if there is a way to include snippets, like including whole documents.nikoloz– nikoloz2015-02-04 07:30:36 +00:00Commented Feb 4, 2015 at 7:30
-
Write all those snippet as a function in a file and call those functions instead of "include" all the time. And dont forgot to include the file at the top of your code. Hope this help function Snip1{} function Snip2{} function Snip3() include_once("SnipCollection.php")Abhilash Cherukat– Abhilash Cherukat2015-02-04 07:33:05 +00:00Commented Feb 4, 2015 at 7:33
-
thanks, looks like there is no way to include() snippets directly.nikoloz– nikoloz2015-02-04 07:35:57 +00:00Commented Feb 4, 2015 at 7:35
Add a comment
|
1 Answer
You can do it with 2 approach:
- You can go with @blckbird idea and put your code in a new file and just include it.
- You can create a file containing a method foo(), with your snip code. include the file and just call that foo().
Exmple:
// helper.php - contain your snip/reusable code
<?php
function startPage($title){
print '
<!DOCTYPE html>
<html>
<head>
<title>'.$title.'</title>
</head>
<body>';
}
function endPage(){
print '
</body>
</html>';'
}
?>
Now your main file include helper.php and call the method you want. // main.php
<?php
include("helper.php");
startPage("My Title");
// do your stuff/coding here
endPage();
?>
hope it helps a bit.