Re: Function in a hash

From: Date: Thu, 13 Jul 2000 08:21:31 +0000
Subject: Re: Function in a hash
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-6394@lists.php.net to get a copy of this message
At 1:23 AM -0600 7/13/00, PHP wrote:
I want to develop a validation routine that you have the database field name as a key and a validation function as the value. I am wanting to validate input by "walking" this validation hash. Is it possible to store references to functions in a hash? Regards, Paul Meagher
I assume you're referring to hash (Perl name) ---> Associative Array (PHP name). If all you want to do is store the name of a validation function - eg: ValidateDate, ValidateIsExisitingCity - or whatever, you can do this by using variable variables (see docs at http://www.php.net/manual/language.variables.variable.php ). For example (untested), ... $ValidateList['city'] = 'ValidateIsExisitingCity'; ... # Execute validation function on 'city' form field # This example assumes these functions return 1 (valid) # or 0 (invalid)...you may have different needs $field_name = 'city'; if ( ${$ValidateList[$field_name]}($$field_name) ) { ... # do something } else { ... # show error message } ... If you want to store the validation code itself in the $ValidateList array, see the eval() function docs at http://www.php.net/manual/function.eval.php For example you could do something like (untested): ... $ValidateFuncList['positive_even_number'] = array( '$IsValid = ($$field_name > 0 ? 1 : 0);', '$IsValid = ($$field_name % 2 == 0 ? 1 : 0);' ); ... # Validate field 'some_number' $field_name = 'some_number'; $validation_type = 'positive_even_number'; while (list(,$func) = each($ValidateFuncList[$validation_type])) { eval($func); if (!$IsValid) { # call error function ... } } Now this is a highly contrived example, and makes me shudder slightly when I think of debugging this. But hey, it's possible. I've even done something like this...once, some time ago. Calling eval() a lot is time consuming, though. You can use double quotes to confuse things even further - that will allow you to perform variable substitutions on variables _before_ the expression is interpreted. So if you want to create undebuggable code without the benefit of assigned or computed GOTOs a la FORTRAN - here's the way :) - steve +--- unix and cats: -----------------------------------------------------+
| Steve Edberg                           University of California, Davis |
| sbedberg@ucdavis.edu                               Computer Consultant |
| http://aesric.ucdavis.edu/                   http://pgfsun.ucdavis.edu |
+----------------------- hard to befriend, but then friends for life! ---+

« previous php.general (#6394) next »