Jump to content

[SOLVED] object.method=function(){} php equivalant?


Zaxnyd

Recommended Posts

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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.