我在Stackoverflow上找不到类似的问题,尽管我相信以前可能有人问过这个问题。
我有一个类,其中包含的方法可能在每页调用多次。每次调用该方法时,我都需要确保公共变量重置为默认值,除非在调用该方法之前已经设置了它们。
使用简单的if条件无法实现这一点,因为无法判断该值是已设置还是仍在上次方法调用时设置
我想不出实现这一点的方法,因为我不能调用我的__construct方法(它设置所有默认值),因为这会覆盖解析的值。但是,我需要重置它们,以防止解析上一次方法调用中的值。
显而易见的答案是给公共变量和返回变量取不同的名称。如果没有其他选择,我会这样做,但我喜欢将变量数量保持在最小
很难用书面形式解释这一点,所以我将用一个我在代码中的意思的例子来更新这个问题。
更新
可能出现问题的示例:
<?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. */
?>
这基本上是一种非常冗长的方式,询问是否可以将类变量重置为其默认值,同时忽略已解析为方法的变量
有几种方法可以实现这一点,但它们都局限于同一个解决方案。在每个重置类中变量的方法之后调用一个函数。最好的方法是在每个方法结束时返回数据。