CodeIgniter:未定义的变量从__construct()获取

时间:2019-06-01 11:54:06

标签: php codeigniter

我正在做一个项目。这是我的代码:

控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace mate
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        string str;
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            str = input.Text;
            MessageBox.Show(str);
        }

        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }
}

模型

public function __construct(){
  parent::__construct();

  $x = $this->input->get('x');
  $this->model->val = $this->model->checkval($x);
}

public function save(){
  // some code to input to database
  echo $this->model->val;
}

(这是简单的版本)

  

消息:未定义变量:y

     

文件名:models / Test_model.php

我要访问public function checkval($x){ switch($x){ case 1 : $y = 10; break; case 2 : $y = 20; break; case 3 : $y = 30; break; } return $y; } ,它将处理save()$this->model->val在Model中已声明为$this->model->val)。 public $val来自$this->model->val,其中$this->model->checkval($x)来自GET方法。但是,它显示此错误。我做错了什么?

1 个答案:

答案 0 :(得分:2)

如果$x不等于1、2或3,则永远不会定义它。为避免这种情况,您需要$y的默认值,如果$x与这些值之一匹配,则可以更改该默认值:

public function checkval($x){
  $y = 0; // This can be false or whatever other value makes sense for your business logic
  switch($x){
    case 1 : $y = 10; break;
    case 2 : $y = 20; break;
    case 3 : $y = 30; break;
  }
  return $y;
}