简体   繁体   中英

php set variable before include and echo it after

I have an Admin class:

<?php
    Class Admin extends Controller{


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

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

    }
?>

the extended Controller class:

<?php

class Controller{

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

}

?>

view class:

<?php
Class View{

    function __construct() {

    }

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

}
?>

so in the test.php file i try to echo $num; but i get nothing...

if i try

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

it echos back 5

whats the problem here?

You can pass associative array to function load as optional parameter and then use extract that array to have variables in scope.

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

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

Or

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

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

As my personal experience shows second method is slightly faster.

In function getPage() all you need to do is:

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

Your $num scope is localized to the function getPage and never makes it as a peice of an object. You can modify the function create a function getPage() to return $num and echo it from test.php, or you could rewrite the code as such:

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

    ?>

You may want to take a look at this: http://www.php.net/manual/en/language.oop5.visibility.php

It'll give you an idea of what visibility options you can implement in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM