EllisLab text mark
Advanced Search
     
2 requests in controller
Posted: 19 November 2012 08:06 PM   [ Ignore ]
Joined: 2012-11-19
1 posts

Hi, i am a new user from CI and in my first controller i look this:

<?php

class Index extends CI_Controller {
  
 
function index()
 
{
  
echo "hi";
  
 
}
  

the resulte is:

hihi

This is normal? And about performance?

 
Posted: 19 November 2012 08:46 PM   [ Ignore ]   [ # 1 ]   [ Rating: 0 ]
Avatar
Joined: 2007-11-28
2435 posts

Don’t name your controller Index, or the index() method will act as a constructor. http://www.php.net/manual/en/language.oop5.decon.php

 
Posted: 19 November 2012 08:53 PM   [ Ignore ]   [ # 2 ]   [ Rating: 0 ]
Avatar
Joined: 2009-02-19
3819 posts

If you name the method the same name as the controller, that is the php4 style of creating a constructor (which gets executed no matter what the request is).

CI uses the reserved ‘index’ method of a controller, which gets accessed if no method name is accessed in the request (http://yoursite.com/controller).

So what’s happening is first the constructor is called (index, because you named your class index), which outputs ‘hi’, then the actual index method is called by CI because there was no method specified, which also outputs ‘hi’.

The way to avoid that is to
1) use php5 constructors and
2) don’t name your controller ‘index’

class Test extends CI_Controller {

  
//PHP5 style constructor
  
public function __construct()
  
{
    parent
::__construct();
  
}

  
public function index()
  
{
    
echo 'this is index';
  
}

  
public function notindex()
  
{
    
echo 'this is NOT the index';
  
}

going to http://yourhost.com/test
triggers index() method and outputs “this is the index”

going to http://yoursite.com/test/notindex
triggers notindex() method and outputs “this is NOT the index”

 

 Signature