0

This is my function:

function rp_md5 ($string)
{
    return md5(strrev($string) . $string);
}

I wish to convert it to a inline anonymous function and I have already tried this code:

$foo = $_POST['u_pwd'];
$pwd = function() use($foo) { 
                return md5(strrev($foo) . $foo);
     };

How I can store new password in the variable $pwd? normally I must call it:

echo $pwd($foo);

sorry for my bad explanation.

4
  • What do you expect about use($foo) ? Commented Jan 10, 2014 at 9:51
  • What's the point of the use? Why not simply $pwd=function($foo) {return md5(strrev($foo) . $foo);}; Commented Jan 10, 2014 at 9:51
  • he does expect $foo to be global variable I guess Commented Jan 10, 2014 at 9:51
  • You can't store the password created by the function $pwd in the variable $pwd if your function is already called $pwd without losing that function definition Commented Jan 10, 2014 at 10:15

1 Answer 1

3

The problem you might expect is that you are trying directly to print $pwd as a variable, instead as a function. This way $pwd will be object of class Closure and cannot be converted to string. You should CALL it.

In your example it will be:

$foo='adasdsadasd';
$pwd=function() use($foo) {return md5(strrev($foo) . $foo);};
echo $pwd();

returning

c22ddae767082a65351481607d0974b7

but with use($foo) you expect $foo to be a global variable, your function is barely reusable.

Using:

$foo='adasdsadasd';
$pwd=function($foo) {return md5(strrev($foo) . $foo);};

will give you the opportunity to call $pwd() with parameters, so you can use it everytime with different param.

In this case you are using:

echo $pwd($foo);

To achieve the same output:

c22ddae767082a65351481607d0974b7

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

4 Comments

please recheck my question
@progfa You must call it $pwd() (if there is use($foo)) or $pwd($foo). What do you need? One more assignation? $foo='adasdsadasd'; $pwd=function($foo) {return md5(strrev($foo) . $foo);}; $pwd1 = $pwd($foo); echo $pwd1;
I want to do it without calling $pwd($foo) and new password must be store in the same variable($pwd), it is not possible?
@progfa If you don't want to CALL why do you use a CALLABLE then? $pwd = md5(strrev($foo) . $foo) is pretty much straightforward for the concept you want to achieve. Otherwise it's not possible to get return value of function (whether closure or not) without calling it

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.