PHP Use Include Inside Function

php

Solution

That use case is explicitly documented:

If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function. An exception to this rule are magic constants which are evaluated by the parser before the include occurs.

IMHO, it's way simpler to keep base paths in constants (you already seem to be doing it to some extent) or even make a full-site search and replace (which is a 30 second task in any decent editor) than rewriting all your included files to use global variables.

Problem

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...

Original source