Reputation: 16948
I was unable to find a similar question on Stackoverflow, although I am sure someone has probably asked this before.
I have a class with methods that may be called several times per page. Each time the method is called I need to make sure the public variables are reset to their defaults, UNLESS they have been set before calling the method.
This cannot be achieved using a simple if condition because there is no way to tell whether the value has been set or is still set from the last method call
I cannot think of a way to achieve this because I cannot call my __construct method (which sets all the default values), as this would overwrite the parsed values. However, I need to reset them to prevent values from the last method call from being parsed.
The obvious answer is to give different names to the public variables and the return variables. I will do this if there is no other option but I like to keep the number of variables to a minimum
It is very hard to explain this in writing so I will update this question with an example of what I mean in code.
UPDATE
An example of where a problem may occur:
<?php
class test{
public $return_array;
public $return_string;
public $return_bool;
function __construct(){
// Set the default values
$this->return_array = false;
$this->return_string = false;
$this->return_bool = false;
}
public function method(){
// ... do something
$array = array('test');
$string = 'test';
$bool = true;
// Only return variables if asked to
$this->return_array = $this->return_array ? $array : NULL;
$this->return_string = $this->return_string ? $string : NULL;
$this->return_bool = $this->return_bool ? $bool : NULL;
return;
}
}
// Initiate the class
$test = new test;
// Call the method the first time with one parameter set
$test->return_array = true;
$test->method();
// Print the result
print_r($test->return_array);
// MOST OBVIOUS ANSWER WOULD BE TO RESET VARIABLES HERE LIKE SO
$test->reset(); // HOWEVER, I DO NOT WANT TO HAVE TO CALL THIS EACH TIME I CALL THE METHOD, HERE LIES MY PROBLEM!
// Call the method again with different parameters
$test->return_string = true;
$test->return_bool = true;
$test->method();
// Print the result
echo $test->return_array;
echo $test->return_bool;
/* The problem lies in the second call of the method because $test->return_array has not been reset to its default value. However, there is no way to reset it without affecting the other variables. */
?>
This is basically a very long winded way of asking whether it is possible to reset a classes variables to their default values, whilst ignoring the ones that have been parsed to the method being called
Upvotes: 2
Views: 1862
Reputation: 16948
There are several ways to achieve this but they all bottle down to the same solution. Calling a function after each method that resets the variables within the class. Best way to do this is at the end of each method before the data is returned.
Upvotes: 1