Wh1T3h4Ck5
Wh1T3h4Ck5

Reputation: 8509

Passing local user-defined function (custom filter) as parameter to the class method?

I'm wondering is it possible somehow?

sample code

class CustomFilter {
  ...
  function FilterData($data, $function_name) {
    # here I want to execute that function against $data argument
    }
  ...
  }

function add2($x) {
  return $x + 2;
  }

$fd = new CustomFilter;
$fd->FilterData(5, ‘add2’);

I can pass function name and execute it using eval() outside of class, but inside the class that function is not visible. Is it any way to make user-defined function work inside the class?

What's the idea?

Using class constructor user passes configuration array into class. Part of array may contain different filter parameters, example:

config array

$cfg = array(
  'image' => array(
    'params' => array(
      '+src' => 'string[filter:url]',
      'maxwidth' => 'integer[filter:1+]',
      'byte' => 'integer[filter:0-255]',
      'alt' => 'string',
      'align' => 'string[values:left|right|center]',
      'binary' => false
      ),
    ...
    ),
  ...
  );

Filter parameters define filter criteria for some input fields. In this example 'string[filter:url]' calls some inner method to check if parameter 'src' is valid url parameter, 'integer[filter:1+]' checks if value is integer greater than 1, 'false' means "don't filter value". But one possible value is 'string[customfilter:myfunction]' and that means "check argument with user-defined function myfunction".

I need to set local function name as string and execute it inside the class.

Any suggestions? Thanks in advance.

Upvotes: 0

Views: 415

Answers (2)

rid
rid

Reputation: 63482

You can call the function with call_user_func_array() or call_user_func():

function FilterData($data, $function_name) {
  call_user_func($function_name, $data);
}

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382746

You can call it like this:

$function_name($data);

Inside your dataFilter function.

Example:

class CustomFilter {
  function FilterData($data, $function_name) {
     $function_name($data);
  }
}

function add2($x) {
  echo $x + 2;
}

$fd = new CustomFilter;
$fd->FilterData(5, 'add2');

Result:

7

Upvotes: 2

Related Questions