CodeIgniter Forums
Can i pass params into a controllers __construct() function? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Can i pass params into a controllers __construct() function? (/showthread.php?tid=51963)



Can i pass params into a controllers __construct() function? - El Forum - 05-24-2012

[eluser]coldscooter[/eluser]
Example:

public function __construct($id=null){
parent::__construct($id);

die($id);
}

The param that i pass in the uri is never picked up by the __construct function.


Can i pass params into a controllers __construct() function? - El Forum - 05-24-2012

[eluser]LifeSteala[/eluser]
Hello,

Please remember to place code within builtin CODE tags for better readability.

To accomplish your goal, ensure you're URI Class Library is loaded and you can do the following:

Note: code is untested.

Code:
public function __construct()
{
  parent::__construct();
  
  // Replace segment (n)
  $id = $this->uri->segment(n);

  die($id);
}

Hope that helps.


Can i pass params into a controllers __construct() function? - El Forum - 05-24-2012

[eluser]PhilTem[/eluser]
And to answer your topic's question: No, you can't pass arguments to the controller's __construct() method. If you want to know more about it, have a look at codeigniter/core/CodeIgniter.php and the path of the request from the index.php through all other files until it reaches you controller. Then you should be able to answer your question by yourself Wink


Can i pass params into a controllers __construct() function? - El Forum - 05-24-2012

[eluser]InsiteFX[/eluser]
PhilTem is correct.

But you can pass parameters through the constructor in your own libraries.
For models you need to create an intialization method and pass then in thrugh it.