laravel php静态数组变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23207306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php static array variables
提问by Ludger
I currently have the following code:
我目前有以下代码:
public static $validate = array(
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required|email'
);
public static $validateCreate = array(
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required|email',
'password'=>'required|min:6'
);
I would like to know if its possible to reference the first static validate array and just add the extra one validation rule without rewriting the whole rule as I am currently doing.
我想知道是否可以引用第一个静态验证数组并只添加额外的验证规则而不像我目前所做的那样重写整个规则。
I know you can not reference any variables from static declarations but I would just like to know if there are any better ways of storing model validation rules in a model.
我知道您不能从静态声明中引用任何变量,但我只想知道是否有更好的方法在模型中存储模型验证规则。
回答by vvanasten
You can use array_mergeto combine $validate
and just the unique key/value of $validateCreate
. Also, since you are using static variables you can do it like the following with all of the code in your model PHP file:
您可以使用array_merge来组合 .$validate
的唯一键/值$validateCreate
。此外,由于您使用的是静态变量,因此您可以使用模型 PHP 文件中的所有代码执行以下操作:
class User extends Eloquent {
public static $validate = array(
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required|email'
);
public static $validateCreate = array(
'password'=>'required|min:6'
);
public static function initValidation()
{
User::$validateCreate = array_merge(User::$validate,User::$validateCreate);
}
}
User::initValidation();
回答by afarazit
You can add the extra field in your static array directly when needed, for example
例如,您可以在需要时直接在静态数组中添加额外的字段
function validate()
{
if($userIsToBeCreated)
{
static::$validate['password'] = 'password'=>'required|min:6';
}
// stuff here
}