Zaxnyd Posted June 13, 2007 Share Posted June 13, 2007 I have a form class which offers basic default validation for each input method, but I'd like to be able to override the validate() function with any given logic (without re-writing the class each time). In javascript, it is possible to simply redeclare a function, such as inputElement.validate = function(){ return this.value != "invalid value"}; which would work like a freaking charm but alas PHP does not offer this syntax. Is there an equivalent or workaround that anyone knows of? I tried eval(), but it won't work, since it's impossible to access the object's variables from within the eval string. Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/55355-solved-objectmethodfunction-php-equivalant/ Share on other sites More sharing options...
Zaxnyd Posted June 13, 2007 Author Share Posted June 13, 2007 Answered my own Q much more quickly than I'd thought I would/could. So here's the answer for you curious readers. <?php class InputElement { var $customValidation; var $id; function InputElement($id){ $this->id = $id; } function validate(){ if(isset($this->customValidation)) return call_user_func($this->customValidation, $this); return "normal validation for ".$this->id; } } $input = new InputElement("input1"); echo $input->validate()."<br>\n"; echo "adding custom validation...<br>\n"; $input->customValidation = create_function('$obj', 'return "custom validation for ".$obj->id;'); echo $input->validate()."<br>\n"; ?> Outputs: normal validation for input1 adding custom validation... custom validation for input1 Quote Link to comment https://forums.phpfreaks.com/topic/55355-solved-objectmethodfunction-php-equivalant/#findComment-273601 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.