Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Use Include Inside Function

Tags:

php

Im trying to make a function that I can call as follows,

view( 'archive', 'post.php' );

and what the function really does is this.

include( 'view/archive/post.php' );

The reason for this is if in the future I expand the directory to be view/archive/another_level/post.php I dont want to have to go back everywhere in my code and change all the include paths.

Currently this is what i have for my function, except it appears that the include is being call inside the function, and not being called when the function is called...

function view( $view, $file )
    {
        switch ( $view )
        {
            case 'archive'  : $view = 'archive/temp';   break;
            case 'single'   : $view = 'single';     break;
        }

        include( TEMPLATEPATH . "/view/{$view}/{$file}" );
    }

How can I get this function to properly include the file?

EDIT:

There were no errors being displayed. Thanks to @Ramesh for the error checking code, ini_set('display_errors','On') I was able to see that there were other 'un-displayed' errors on the included file, which appeared to have caused the file not to show up...

like image 473
cnotethegr8 Avatar asked Apr 12 '12 09:04

cnotethegr8


People also ask

How we use include () and require () function in PHP?

The include (or require ) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website.

What is the difference between the include () and require () functions?

include() Vs require() The only difference is that the include() statement generates a PHP alert but allows script execution to proceed if the file to be included cannot be found. At the same time, the require() statement generates a fatal error and terminates the script.

What is the difference between include and include_once in PHP?

The include() function is used to include a PHP file into another irrespective of whether the file is included before or not. The include_once() will first check whether a file is already included or not and if it is already included then it will not include it again.


1 Answers

Here's one way you could solve the problem:

change the way you call your function so it looks like this:

include( view('archive','post') );

and your function would look like this:

<?php
function view( $view, $file )
{
    switch ( $view )
    {
        case 'archive': $view = 'archive/temp'; break;
        case 'single' : $view = 'single';       break;
    }

    return TEMPLATEPATH . "/view/{$view}/{$file}";
}
?>
like image 168
code_monk Avatar answered Oct 04 '22 08:10

code_monk