2

I have wrote a function that should first output a navigation bar, and after include the page content, I have tried to put the include inside a variable, but it doesn't work and I don't know how to do it, can you help me?

here is the code:

class myclass {
function test() {
    if($_SESSION['logged_in'] == TRUE) {
        $pages = array('news', 'main', 'email', 'switch', 'comments');

        $page = "main";
        if(isset($_GET['page'])) {
            $page = $_GET['page'];
        }

        //navigation bar
        $blah = '<div id="shittynavigationbar"><ul>';
        foreach($pages as $url) {
            $out .= '<li><a href="/?id=admin&amp;action=$url"';
            if($url != $n){
                $out .= ' id="active"';
            }
            $out .= '>' . ucfirst($url) . '</a></li>';
        }
        $out .= '</ul></div><div id="main">';


        //content 
        if(!in_array(basename($action), $pages)) {
            $out .= include('admin/inc/' . $action . '.php');
        } else {
            $out .= 'page not found';
        }

        return $out;
    } else {
        return 'you are not logged in';
    }
}
}
$a = new myclass();
echo $a->test();

Thanks in advance

yes sure
  • 97
  • 2
  • 11

2 Answers2

0

You need to actually fetch the content of the PHP file you're trying to include, either using cURL or file_get_contents() as follows:

//content 
if( !in_array(basename($action), $pages) ) 
{
    $out.= file_get_contents('admin/inc/' . $action . '.php');
} 
else 
{
    $out .= 'page not found';
}
BenM
  • 52,573
  • 26
  • 113
  • 168
  • 1
    but inside the file that I want to include there are some PHP codes, and with `file_get_contents` it won't be run – yes sure May 29 '16 at 13:04
  • Then why have a function to include it at all? You'd be much better having a single function to generate the header, and calling it on the pages. – BenM May 29 '16 at 13:08
0

I have a solution for you but it will change some more

In file $action . ".php" create class

class ActionName { 
     function run(){
          return '';
     }
}

then In your code

 include('admin/inc/' . $action . '.php');
 $actionName = new $action();
 $out .= $actionName->run();

Thank for reading. Hope it help

HoangHieu
  • 2,802
  • 3
  • 28
  • 44