开发者

Is it possible to pass an unset variable to a function or otherwise validate forms without isset()?

I've got a project that passes JSON between the frontend and the backend. So, the frontend PHP would generate the statement { "command" : "getuser", "parameters" : { "userid" : 1 } } and send it to the backend. The backend then executes

if ($command == 'getuser') {
  validate($parameters['userid']);
  if ($this->valid) { <<get the user>> }
}

Validate checks the variable and sets $this->valid. It creates an error message if necessary. I want to create an error message in case the front end passes in { "command" : "getuser", "parameters" : "" }. In this case, $parameters['userid'] is never set, and validate() will complain that it was passed an unset variable.

I've come up with two solutions. The first solution is to set $parameters['userid'] = "unset" before loading in the JSON, and then check for it in the validator. The other solution is to use

if (isset($parameters['userid'])) { 
  val开发者_JAVA百科idate($parameters['userid']);
} 
else { 
  echo("Error"); } 

It'd be nice if validate() could figure out on its own whether or not the variable is there. Is there a more elegant way I should be doing things?


In short, no. The error happens as, rather than after, validate() is called so there is no way for it to intercept that.

It sounds like a better solution would be to have a validateUser() function that is passed in the whole $parameters variable then does the check you're looking for against the 'user_id'. This allows you to to further separate your concerns (validation, versus response).


If you want this style of code, you could pass arg to function by reference
If not, try to use this validate($parameters, 'userid');


You would have to pass $parameters into validate and let it check if userid was there and if not create the error message.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜