简体   繁体   中英

Can not access variables from a function in the view

I'm using a function to generate some HTML in the view. I can not access the data that send form controller within that function.Following is the simplified code.

Controller

$data["var"] = "something";
$this->load->view("the_view",$data);

View

function some(){
   global $var;
   echo $var;
}

some(); //not working
echo $var; //working

I can move this function to the controller. Generate HTML in controller and send the generated HTML to view. But I like to keep HTML stuf in the view. How can I do this?

 You can rewrite your function like this function some($var){ echo $var; } some($var); Hope it will work

You have created an array named as data and var stored into that, so you need to this

function some($data){
   echo $data["var"];
}

some($data);

And in case your data array is global, then

function some(){
   global $data
   echo $data["var"];
}

some();

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