Reputation: 33
When I use the code below it throws an error even though the function looks well formed. (FYI I also tried valid and static prefixes.)
Function call:
foreach ($this->errorList as $field => $error_msg) {
// check for valid input and store cleaned vars
$this->goodInput[$field] = Valid::__($field);
}
Result:
PHP Fatal error: Call to undefined function Valid::email()
Code:
class Valid
{
public static function __($name)
{
// this is what I tried:
// $checkFunction = 'self::' . $name;
// return $checkFunction();
// this works:
// Thank you to fusion3k and Darren
return self::$name();
}
private static function email()
{
//sanitize and validate email field
}
// other methods for other fields
// ...
// default method to sanitize input for display in email
public static function __callStatic($name, $arguments)
{
if (array_key_exists($name, $_POST)) {
$clean_var = trim($_POST[$name]);
$clean_var = stripslashes($clean_var);
$clean_var = htmlspecialchars($clean_var);
return $clean_var;
} else {
return '';
}
}
}
Upvotes: 1
Views: 104
Reputation: 13128
I assume you instantiate your class somewhere properly first right? Well it's best to check that a said method exists, and harness self::
. Also, as @fusion3k said, better to return self::$name()
. Here's an example of what you should be doing:
public static function __($name) {
if(method_exists(new self, $name)) {
return self::$name();
}
}
In all honesty, this isn't the best way for you to be doing it. You should be looking into call_func_user_array()
to manage this kind of implementation properly. Allowing the parsing of arguments to called methods.
Upvotes: 3
Reputation: 910
There is not any object created when you call an static function then Valid functions are not accessible. Try like this
public static function __($name) {
$valid = new Valid ();
return $valid::$name();
}
Upvotes: 0