doushi3819244 2012-02-23 18:22
浏览 37
已采纳

Codeigniter:从网址放置变量的位置

I am developing a stats site in Codeigniter locally. I have a url like localhost/sitename/player/show_profile/PlayerName

I currently have the following:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Player extends CI_Controller
{

  public function __construct()
  {
    parent::__construct();
    $this->load->model('player_model');
    $player_name = $this->uri->segment(3);
  }


  public function index()
  {
        echo "index";
  }

  public function show_profile($player_name)

  {

        $data['player_stats'] = $this->player_model->get_stats( $player_name );
        $this->load->view('player/player_stats', $data);
  }

}

?>

This works, but my question is regarding the $player_name variable. I have $player_name = $this->uri->segment(3); in the __construct so it's available to all of the class methods. Is this the way I should be doing it?

Is this safe?

  • 写回答

2条回答 默认 最新

  • doujianqin5172 2012-02-23 18:58
    关注

    Fist of all, there is no point in assigning the variable in the constructor because it's going to get overwritten. When you pass CI a url like localhost/sitename/player/show_profile/PlayerName, anything passed the method (i.e. PlayerName) get's set as the parameters. Therefore, your variable in

    public function show_profile($player_name){
    

    is already set when you get to your method code.

    Secondly, I agree with Peter's:

    protected $player_name;
    

    for making it globally accessible in the controller. BUT, I don't agree with setting it in the constructor. If you have another method in this controller that passes a variable in that spot, you're going to get the wrong data in there. Set it in the method you called:

    public function show_profile($player_name){
    
        $this->player_name = $player_name;
    
        $data['player_stats'] = $this->player_model->get_stats( $player_name );
        $this->load->view('player/player_stats', $data);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据