CodeIgniter Forums
Trying to understand an example in general topics - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Trying to understand an example in general topics (/showthread.php?tid=69119)



Trying to understand an example in general topics - Cano58 - 10-10-2017

In the general topics section on views it gives this example:

Let’s try it with your controller file. Open it add this code:

Code:
<?php
class Blog extends CI_Controller {

       public function index()
       {
               $data['title'] = "My Real Title";
               $data['heading'] = "My Real Heading";

               $this->load->view('blogview', $data);
       }
}


Now open your view file and change the text to variables that correspond to the array keys in your data:

Code:
<html>
<head>
       <title><?php echo $title;?></title>
</head>
<body>
       <h1><?php echo $heading;?></h1>
</body>
</html>


I'm confused how the view file can access the variable $title without accessing the array that it is in. I would expect it to be something like
Code:
<html>
<head>
      <title><?php echo $data['title']; ?></title>
</head>
<body>
      <h1><?php echo $data['heading']; ?></h1>
</body>
</html>

Are all of the array elements converted into stand alone variables?
Thank you.


RE: Trying to understand an example in general topics - twpmarketing - 10-10-2017

The array $data is extracted by the loader class (library) and each array element is accessible as individual variables inside the view.

The original array ($data) is NOT passed, so it cannot be referenced in your view code.

User Guide (3.0) REFERENCE: file:///home/twp/Dev/CI_3.0/user_guide/libraries/loader.html#class-reference
Scroll down to the view method definition.


RE: Trying to understand an example in general topics - Cano58 - 10-10-2017

Great, thanks.


RE: Trying to understand an example in general topics - dave friend - 10-11-2017

If you want a better understanding, the read the PHP documentation on the extract function. That function is called when views are "loaded".