PHP从类中包含的文件访问同一个类


PHP Access same class from a file included inside the class

这是类:

functions.php

class buildPage {
    public function Set($var,$val){
        $this->set->$var = $val;
    }
    function Body(){
        ob_start();
        include('pages/'.$this->set->pageFile);
        $page = ob_get_contents();
        ob_end_clean();
        return $page;
    }
    function Out(){
        echo $this->Body();
    }
}

这是脚本的主(索引)页。

index.php

include_once('include/functions.php');
$page = new buildPage();
$page->Set('pageTitle','Old Title');    
$page->Set('pageFile','about.php');
$page->Out();

现在,正如您所看到的,它通过类包含about.php文件,实际上是在类内部。

现在,我想访问同一个buildPage()类来更改页面标题。

关于.php

<?php
$this->Set('pageTitle','New Title');
echo '<h1>About Us</h1>';
?>

但不幸的是,什么也没发生。

请花几分钟时间给我一些帮助!

好。我自己设法解决了这个问题。

更改函数Body()和Out()如下:

function Body(){
    $pageFile = $this->Get('pageFile');
    if(empty($pageFile)){
        $pageFile = 'home.php';
    }
    $page_path = 'pages/'.$pageFile;
    ob_start();
    include($page_path);
    if(!empty($page_set_arr) && is_array($page_set_arr)){
        foreach($page_set_arr AS $k=>$v){
            $this->Set($k,$v);
        }
    }
    $page = ob_get_clean();
    return $page;
}
function Out(){
    $body = $this->Body();
    echo $this->Header();
    echo $body;
    echo $this->Footer();
}

然后将about.php文件更改如下:

<?php
$page_set_arr = array(
                    'pageTitle' => 'About Us'
                );
?>
<h1>About Us</h1>