簡體   English   中英

php在包含之前設置變量,並在之后將其回顯

[英]php set variable before include and echo it after

我有一個管理員班:

<?php
    Class Admin extends Controller{


        function __construct() {
            parent::__construct();
        }

            function getPage(){
                $num = 5;
                $this->view->load('test');
            }

    }
?>

擴展的Controller類:

<?php

class Controller{

    function __construct() {
        $this->view = new View();
    }

}

?>

查看類別:

<?php
Class View{

    function __construct() {

    }

    public function load($file){
        include($_SERVER["DOCUMENT_ROOT"].'/main/views/'.$file.'.php');
    }

}
?>

所以在test.php文件中,我嘗試echo $num; 但我什么也沒得到...

如果我嘗試

$num = 5;
include($_SERVER["DOCUMENT_ROOT"].'/main/views/test.php');

它回響5

這里有什么問題?

您可以將關聯數組作為可選參數傳遞給函數load ,然后使用extract該數組在范圍內包含變量。

public function load($file, $data = array()){
    extract($data);

    include($_SERVER["DOCUMENT_ROOT"].'/main/views/'.$file.'.php');
}

要么

public function load($file, $data = array()){
    foreach ($data as $key => $val)
        ${$key} = $val;

    include($_SERVER["DOCUMENT_ROOT"].'/main/views/'.$file.'.php');
}

根據我的個人經驗,第二種方法稍快一些。

在函數getPage()您需要做的是:

$this->view->load('test', array('num' => 5));

您的$ num范圍已本地化為getPage函數,並且永遠不會將其作為對象的對象。 您可以修改函數以創建函數getPage()以返回$ num並從test.php中回顯它,或者可以這樣重寫代碼:

<?php
        Class Admin extends Controller{


            function __construct() {
                parent::__construct();
            }

            public $num = 5;

            function getPage(){
                    $this->load->view('test');
                }

        }

    class Controller{

        function __construct() {
            $this->view = new View();
        }

    }

    Class View{

        function __construct() {

        }

        public function load($file){
            echo "I shall skip the file include";
        }

    }

    $test = new Admin();
    echo $test->num;

    ?>

您可能需要看看以下內容: http : //www.php.net/manual/zh/language.oop5.visibility.php

它將使您對將來可以實現的可見性選項有所了解。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM