My question stems from a model I am writing to construct queries from predefined search objects that contain 'criteria', each search has a property $search->criteria
that is an array of criteria objects....
Criteria (
"name" => "name", //name of given field to be searched
"expr" => "expr", //could be "<=" ">=" "="
"s_value" => "value" //value to be searched with
)
and the part of my search function that is adding the proper where statements to the query...
if(count($criteria)) {
foreach($criteria as $crit) {
$this->{$crit['name']}($crit['s_value'],$crit['expr']);
}
}
And now finally the function that loop is calling, 'name' here corresponds with whatever the criteria object has set as $criteria['name']....
function name($value,$expr = '=') {
$this->db->where('specific_field_name '.$expr,$value);
}
Now for the question..
I want to create a variable inside 'name' that will persist beyond a single execution, so for instance, if I have 2 criteria with the same name and it executes twice, I want to maintain a variable in it's scope for multiple executions.
EDIT
What I WANT to do. I have multple functions like this that all need their own counters.
function name($value,$expr = '=') {
if(isset($count))
$this->db->or_where('specific_field_name '.$expr,$value);
$count++;
}
else {
$count = 1;
$this->db->where('specific_field_name '.$expr,$value);
}
}
Ideas?
SOLUTION
if(count($criteria)) {
$criteria_count = array()
foreach($criteria as $crit) {
if(isset($criteria_count[$crit['name']])) {
$criteria_count[$crit['name']]++;
}
开发者_如何学C else {
$criteria_count[$crit['name']] = 1;
}
$this->{$crit['name']}($crit['s_value'],$crit['expr'],$criteria_count[$crit['name']]);
}
}
Changed the main search function to maintain a $criteria_count
array with the names as keys and passing the count down to the specific functions.
You could use the global
statement if you really want to do it this way.
Edit: here is how I might pass count into name and keep track of it that way.
At beginning of search function: $count = 0;
if(count($criteria)) {
foreach($criteria as $crit) {
$count = $this->{$crit['name']}($crit['s_value'],$crit['expr'],$count);
}
}
And then the name function:
function name($value,$expr = '=',$count) {
if($count > 0)
$this->db->or_where('specific_field_name '.$expr,$value);
$count++;
}
else {
$count = 1;
$this->db->where('specific_field_name '.$expr,$value);
}
return $count;
}
精彩评论