2016-11-16 127 views
0

我想用下面的函數設置一個標題,然後調用另一個函數,這樣我就可以渲染視圖,但看不到標題。這裏是我的代碼:PHP調用兩個函數,但保存第一個函數的變量?

$indexPage = new View(); 
$indexPage->setPageTitle('This is the title'); 
$indexPage->render('index'); 

這是我的觀點類:

class View { 

    private $title; 

    public function render($file) { 
     require '/view/header.php'; 
     require '/view/'.$file.'.php'; 
     require '/view/footer.php'; 
    } 

    public function setPageTitle($title) { 
     $this->title = $title; 
    } 

} 

那麼我會訪問我的網頁上:

的index.php從另一個文件

片段:

<?php echo $this->title ?> 

但它不顯示。

+0

它應該按照您的情況在這裏工作。爲了進行調試,請打開錯誤報告並查看是否有任何錯誤 – Thamilan

+0

@Thamilan從不知道這是現在的工作,謝謝! – baileyJchoi

回答

1

是的,它不會顯示。如果您在代碼snipet中提到的index.php中創建了視圖對象,那麼您可以調用<?php echo $indexPage->title ?>否則,當您渲染視圖模板時,必須像大多數MVC那樣傳遞數據。

注意:如果您想直接訪問它,請將title變量設爲public,否則寫另一個公共函數並返回私有成員。

+0

'$ indexPage-> title'不起作用 – baileyJchoi

+0

沒關係現在這工作謝謝! – baileyJchoi

0

嘗試<?php echo $indexPage->title ?>並將private $title;更改爲public $title;

私人變量不能在他們所在班級之外訪問。

相關問題