0

I'm working on a project. Here's my code :

Controller

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;
}

Model

public function checkval($x){
  switch($x){
    case 1 : $y = 10; break;
    case 2 : $y = 20; break;
    case 3 : $y = 30; break;
  }
  return $y;
}

(That's the simple version)

Message : Undefined variable: y

Filename : models/Test_model.php

I want to access save(), and it will process the $this->model->val ($this->model->val has been declared as public $val in Model). $this->model->val is get from $this->model->checkval($x) where $x is get from GET method. But, it shows this error. What did I do wrong?

1
  • try $_REQUEST['x'] in constructor Commented Jun 1, 2019 at 11:58

1 Answer 1

2

If $x is not equal to 1, 2, or 3 it is never defined. To prevent this you need a default value for $y which then can be changed if $x matches one of those values:

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Please correct controller to correct it: parent::__construct();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.