1

I have an anonymous function:

$rules = array(
    'asdf' => array('required'),
    'zxcv' => array('function ($data) {
    return strtoupper($data); }'),
);

found in the the 'zxcv' key of the $rules array. I need to call this function and I've already tried a few things including:

$rules['zxcv']('mydata');

and

array_map($rules['zxcv'], 'mydata');

and

call_user_func($rules['zxcv'], 'mydata'); to no avail

any help would be appreciated

5
  • 1
    the reason why you're not able to call it is simply because it's not actually a function. What you have there is a string. Not a function. Commented Mar 26, 2014 at 18:51
  • That's a string, not an anonymous function. Commented Mar 26, 2014 at 18:52
  • well how do I use it then? Commented Mar 26, 2014 at 18:52
  • i didn't know there was a difference Commented Mar 26, 2014 at 18:53
  • 1
    You can either eval() it (not recommended) or make it a normal function (drop the quotes). Commented Mar 26, 2014 at 18:53

2 Answers 2

4

That's a string, not a function. Lose the quotes and make it like so:

$rules = array(
   'asdf' => array('required'),
   'zxcv' => function($data) { return strtoupper($data); }
);

Usage with array_map():

array_map($rules['zxcv'], $someArray);

Calling the function individually:

echo $rules['zxcv']('foo'); // FOO

Demo

Sign up to request clarification or add additional context in comments.

6 Comments

is it really that simple?
@user3207727 Try it and see ;)
yes, it is that simple. You made it a string... and a string is not evaluated to actual PHP code.
@user3207727: Yes, really. It's that simple :)
it's working, I'm using $rules['zxcv']('foo') and its fine, thanks again, but one thing, who should I upvote? I'm not real familiar with how this forum thing works
|
3

What you have there is a string, not a function.

What you're looking for is:

$rules = array(
   'asdf' => array('required'),
   'zxcv' => function($data) { return strtoupper($data);}
);

and you can then call it like this:

$rules['zxcv'](YOUR_DATA);
array_map($rules['zxcv'], YOUR_DATA);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.