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 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题