TheFilmGod Posted August 29, 2009 Share Posted August 29, 2009 I'm working on a huge website project. And to make my life easier in the long run, I decided to make a custom validation class. <?php class formValidator { // Assume all errors public $valid = 0; // Function to display value of variable function displayValueFor($value) { echo $this -> {$value}['value']; } // Function to display (error) message for variable { function displayErrorMsg($value) { echo $this -> {$value}['msg']; } // Email function validateFirstName($value, $var_name) { // Create array of this value public ${$var_name} = array('value' => $value, 'msg' => 'undefined', 'valid' => 0); // Validate first name if ( !empty($value)) { $regex = "/^[A-Za-z][A-Za-z ]{2,49}$/"; if ( preg_match($regex, $value)) { $this -> {$var_name}['valid'] = 1; $this ->{$var_name}['msg'] = 'Valid!'; } else { $this -> {$var_name}['msg'] = 'The name must be between 3-20 characters long. Only letters are considered as valid characters.'; } } else { $this -> {$var_name}['msg'] = 'The first name was left blank.'; } } } // Test $first_name = 'Greg'; $page_validator = new formValidator(); $page_validator -> validateFirstName($first_name, 'first_name'); $page_validator -> displayErrorMsg('first_name'); ?> I do some unique and possibly illegal stuff. I get a syntax error for "public ${$var_name}. What I want to do is run a variable through the validation once, create a new attribute in the class for that variable, cache its value , error message, and validation check (true, false) in an array, all as array elements of the new attribute. The obvious solution to this would be to run the variable through the validation class each time I wanted to know the error message, but this isn't efficient. I would be looping through one function 2 or even 5 times to do the same work that I could do in once in a normal php function. I hope I'm making sense. I'm really bad at oop. And I pressed for time, so I might end up using old fashioned php functions if this doesn't work out. Quote Link to comment https://forums.phpfreaks.com/topic/172430-first-oop-code/ Share on other sites More sharing options...
KevinM1 Posted August 30, 2009 Share Posted August 30, 2009 I'm not really a fan of an object having dynamic data members. It can be hard to write a public interface for, and can lead to confusion over what an object should contain. Read this message for an idea on how to implement validation via OOP: http://www.phpfreaks.com/forums/index.php/topic,188111.msg845281.html#msg845281 I also suggest reading through that entire thread, as the overall discussion is pretty informative. Quote Link to comment https://forums.phpfreaks.com/topic/172430-first-oop-code/#findComment-909093 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.