将数组键和值提取为变量

将数组键和值提取为变量

问题描述:

As you know, Codeigniter is a great PHP framework, I'm trying to make my own framework. Here is a problem. I really like the $data functionality in Codeigniter and I want to make it happen in my framework. Question is, how it works. Here is what it does :

  1. you make a array like this :

    $data['title']= 'My Name';
    
  2. then you can use this variable like this in view :

    $title ;
    

How I can make a variable like $data ?

如您所知,Codeigniter是一个很棒的PHP框架,我正在尝试创建自己的框架。 这是一个问题。 我非常喜欢Codeigniter中的 $ data code>功能,我想在我的框架中实现它。 问题是,它是如何工作的。 以下是它的作用: p>

  1. 你创建一个这样的数组: p>

      $ data ['  title'] ='我的名字'; 
      code>  pre>  li> 
     
  2. 然后你可以在视图中使用这个变量: p>

      $ title; 
      code>  pre>  li> 
      ol> 
     
     

    如何制作像 $ data ? p> div>

What you are looking for is turning array keys into variables. There's one in-built function given to do this.

extract() - Import variables into the current symbol table from an array

$data['x'] = "Value";
extract($data,  EXTR_PREFIX_SAME, null);
echo $x;

Go through docs and explore how you want to use it.

Your question is a bit vague, and also don't write your own framework if you are struggling with this question.

But I think what you are asking is how does CI access the variables in $data (without $data['var_name'];) ?

So if you pass:

$data = array("title" => "a page title");

in your view you can just . Is that your question - how to do that?

it is simple.

function view($data=array(),$file="your-view-file.php") {
extract($data); 
include($file);
}

because extract is in the same scope as the include().

Honestly though, just go through the CI files and work this stuff out...