0

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.

4
  • 4
    why dont you put that snippet in an extra file? Commented Feb 4, 2015 at 7:13
  • i just wonder if there is a way to include snippets, like including whole documents. Commented 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") Commented Feb 4, 2015 at 7:33
  • thanks, looks like there is no way to include() snippets directly. Commented Feb 4, 2015 at 7:35

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.