0

I'm receiving prepared function as strings like these:

"\app\models\AddrModel::getText('A_00001724');"

Now I need to convert and run this string as static function call, to retrieve the value if the A_00001724 id.

How do I do that?

PS: When I call it as $value = new $function; I get

Class '\app\models\AddrModel::getText('A_00001724')' not found

since it's not just class. It`s static function with class :/

6
  • 1
    What about $value = eval( 'return '."\app\models\AddrModel::getText('A_00001724');" ) ? Commented Jun 5, 2015 at 15:45
  • @Mat I checked the docs, eval doesn't return any value, so this wont work for me. Commented Jun 5, 2015 at 15:52
  • eval does return a value if the evalued code returns a value. My test case is : $func = "sprintf('%s %s', 'hello', 'world');"; $value = eval('return '.$func); print_r($value); // echo "hello world" Commented Jun 5, 2015 at 15:53
  • Yes, thank you. I also found the same solution: $value = eval('return '.$function.';');. You should put it as answer, so I can accept it. Commented Jun 5, 2015 at 15:55
  • just notice that eval is a bit risky in some cases so make sure the $function value is being checked and validated prior to usage. Commented Jun 5, 2015 at 15:56

1 Answer 1

2

eval() can be used to execute php code in a string. Eval() returns a value if the executed code returns a value.

So, in the case above :

$func = "\app\models\AddrModel::getText('A_00001724');";
$value = eval('return ' . $func);
print_r($value);
Sign up to request clarification or add additional context in comments.

1 Comment

it is needless to say that eval is a very bad Idea, and perhaps you should change your approach in solving your problem

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.