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.

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.