The question I originally had has been asked (and answered) several times before1,2,3,4 : how do I call a variable defined in a different function in the same class - but couldn't get the following to work:
class my_model extends CI_Model {
public $myvar;
public function test1()
{
$this->myvar = "Hello world";
}
public function test2()
{
return strtoupper($this->myvar);
//And have tried:
// return my_model::test1()->$myvar
}
}
Changing test1
to act as a setter
function (and calling that function to access the variables) does work; changing my test1
to:
public test1()
{
$this->myvar = "Hello world";
return $this->myvar;
}
and test2
to:
public function test2()
{
$a = $this->test1();
return strtoupper($a);
}
This question has a comment that controller methods in CodeIgniter work slightly differently from regular PHP class methods
. Is this also the case for model
classes: if so is this the reason I need to call test1
first (and that variables in other methods aren't accessible), or is there something else I've failed to understand?!
Real life example
This is what I'm actually trying to do - please tell me if there's a better way to do it!
I was going to split up the methods which run a select *
query and a query which returns a count
, and since I'm using CI's QueryBuilder
class this seemed the obvious solution:
class my_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function test1()
{
return $this->db->get('Table1');
}
public function test2()
{
return $this->test1()->result_array();
}
public function test3()
{
return $this->test1()->num_rows();
}
}
However, cale b made a comment that this might feel a bit jenky - how else would it be done?