Home » Php » php – Should I use Controller Argument or uri->segment?

php – Should I use Controller Argument or uri->segment?

Posted by: admin July 12, 2020 Leave a comment


Should use Controller Argument

function view($post_id) {

or uri->segment

function view() {
    $post_id = $this->uri->segment(3);

Just for simple blog post ID. Is there a difference?

How to&Answers:

I would use the controller argument.

Then if you ever had to move the code and put it in a sub-directory it would still work, where as the segment method would not.


No, there is no difference in this case. Use Controll Argument when you can. It allows you to mess more with routes and move the controller file.

If you wish to use uri, consider using $this->uri->rsegment(3); instead since it allows you to bind routes without it affecting the rsegment.

The best thing about CodeIgniter is that it’s up to you which solution you prefer. I prefer using argument since it allows me to quickly understand how the values in the url affects the function without having to look through the function; I see the values at the top.

If you’re afraid of creating error messages, consider setting it to

function view($post_id = NULL) {

instead. It will prevent errors if you access the url without a post_id.