I am writing a validation class in PHP which I would like to be extendible without editing the main parent class. I have provided a simplified version below of what I hope to achieve. I am passing a function/method name to validate() which first checks if it exists and if it does invokes it to check the variable I passed is valid. I am new to OOP and having problems with scope / visibility as I’m unable to get any custom validation rules in the child class working without hardcoding the name of the child class in the parent class. What is the best way to go about this? Many thanks for any assistance you can provide.
$rule = "number";
$var = "abcdef";
class Validation
{
public static function validate($rule, $var) {
if (is_callable("self::{$rule}")) {
return self::$rule($var);
}
}
protected static function number($var) {
return (preg_match("/^[0-9]+$/i", $var));
}
}
class MyRules extends Validation
{
public static function letter($var) {
return (preg_match("/^[a-zA-Z]+$/i", $var));
}
}
print MyRules::validate($rule, $var) ? "Valid!" : "Not valid!"; // Not valid!
Firstly, you can prevent overriding of the
validatemethod using thefinalkeyword:As for not being able to call static methods of subclasses, this can be done using Late Static Binding: