题
假设我有课...
class Main { $prop1 = 2; $prop2 = 23; ... $prop42 = "what"; function __construct($arg_array) { foreach ($arg_array as $key => $val) { $this->$key = $val; } } }
说我创建和对象...
$attributes = array("prop1"=>1, "prop2"=>35235, "prop3"=>"test"); $o = new Main($attributes);
如果用户不提供默认属性值,则提供默认属性值。但是,如果我想对用户提供的对象属性值执行任意限制,该怎么办?如果我想执行该怎么办 $prop1
是 int
, ,不少于1,不超过5个。 $prop42
类型 string
, ,不少于“ A”,不超过“ Z”?为此,使用任何可能的语言功能或技巧,将脚本尽可能简短和甜蜜,最干净的方式是什么?
我陷入了困境 __construct()
检查提供的值与类似构建的规则数组
$allowable = array( "prop1" => array( 'type' => 'int', 'allowable_values' => array( 'min' => 1, 'max' => 5 ) ), "prop2" => array( 'type' => 'int', 'allowable_values' => array( 1, 235, 37, 392, 13, 409, 3216 ) ), ... "prop42" => array( 'type' => 'string', 'allowable_values' => array( 'min' => 'A', 'max' => 'Z' ) ) );
如您所见 prop2
, ,我的验证功能开始对许多“ If-if-titerrate-Again”块变得非常混乱,因为我不仅要考虑范围,而且要考虑允许的值列表。有了验证代码和此规则数组,我的脚本变得相当笨重。
问题是,我如何构建我的类或类属性,验证代码或脚本的任何其他方面,以尽可能短而简洁,以允许属性范围和价值执行?是否有语言功能或技巧可以更优雅地处理?我到达了砖墙,这是该语言的极限吗?是否有其他语言的示例可以轻松实施可以提供一些线索?
解决方案
前几天我遇到了类似的问题。这是我要做的:
private $props;
private $rules;
function __construct($params) {
// or you can get the rules from another file,
// or a singleton as I suggested
$this->rules = array (array('type' => 'range', 'min' => 10, 'max' => 20),
array('type' => 'in_set', 'allowed' => array(1,2,3)));
for ($i=0; $i<count($params); $i++) {
if ($this->check($params[$i], $this->rules($i))
$this->props[$i] = $params[$i];
else
throw new Exception('Error adding prop ' . $i);
}
}
function check($value, $rule) {
switch($rule['type']) {
case 'range':
return ($rule['min'] <= $value && $value <= $rule['max']);
case 'in_set':
return (in_array($value, $rule['allowed']));
// and so on
}
}
如果您有很多参数,则可以使用一个数组并迭代。如果您的验证规则始终是相同的,则可以将它们放入单独的文件中并加载该文件或其他任何内容。
编辑:顺便说一句,在PHP中测试类型确实没有意义。这两者都不是非常可靠和不必要的。
编辑2:您可以使用一个 辛格尔顿:
其他提示
获取器和固定器
class Main {
private $prop1;
private $prop2;
private $prop3;
public function __construct( $p1 , $p2 , $p3 )
{
$this->setProp1($p1);
$this->setProp2($p2);
$this->setProp3($p3);
}
public function setProp1($p1)
{
// conditional checking for prop1
if(!$ok) throw new Exception('problem with prop1');
$this->prop1 = $p1;
}
//.. and so on
}
不隶属于 StackOverflow