繁体   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