PHP调用两个函数,但保存第一个函数的变量


PHP call two functions but save variable from first one?

我试图用下面的函数设置标题,然后调用另一个函数,这样我就可以渲染视图,但在我看不到标题之后。下面是我的代码:

从另一个文件:

$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 ?>

但是没有显示

不显示。如果你在index.php中创建了视图对象,如代码片段所述,然后你调用<?php echo $indexPage->title ?>,否则当你渲染视图模板时,你必须像大多数MVC一样传递数据。

注意:如果你想直接访问title变量,就把它设为public,否则再写一个public函数,返回私有成员。

尝试<?php echo $indexPage->title ?>并将private $title;更改为public $title;

私有变量不能在类外访问