0

For example, post name is 'New feature'. I need to get output Post name is New feature using eval()

$post = Post::find($id);
$str = 'Post name is $post->name';
eval("\$str = \"$str\";");

This code outputs Post name is {"id":1,"name": "New feature"}->name. How to get exactly name of post with eval, not whole object?

NOTE

do not pay big attention to what is outputs exactly, it was taken like abstract, i need to take attribute of object using eval, because $str will be dynamic

5
  • Try this : $str = 'Post name is '.$post->name; Commented Jul 27, 2021 at 8:09
  • Using eval in this context is just an invitation to have arbitrary code execution on your server Commented Jul 27, 2021 at 8:18
  • @apokryfos admin using editor will create different pages, so i need to get some values from db and put it to content Commented Jul 27, 2021 at 8:20
  • That doesn't explain why you think eval is necessary Commented Jul 27, 2021 at 8:21
  • @DanabekDuisekov in that case you can use placeholders in the content and replace them when outputting. No eval required. for example use [post.name] in the content and str replace all when outputting. Commented Jul 27, 2021 at 8:28

2 Answers 2

1
$str = 'Post name is ' . $post->name;
echo $str;

I don't recommend using eval()...

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

2 Comments

do not pay big attention to what is outputs exactly, it was taken like abstract, i need to take attribute of object using eval, because $str will be dynamic
In 99,9% of the cases there is an other solution than eval(). So always try to avoid it. Even if the $str is dynamic, I don't think eval will be the best, safest solution.
1

This happens because $post will be evaluated directly in the eval function. Thus outputing {"id":1,"name": "New feature"}. Using eval is not recommended and certainly not for outputting a simple string. You can go with this instead:

$post = Post::find($id);
$str = "Post name is {$post->name}";
echo $str;

If you really need eval for some reason (there is probably a better way than eval), then this should do it:

$post = Post::find($id);
$name = $post->name;
$str = 'Post name is'.$name;
eval("\$str = \"$str\";");

2 Comments

do not pay big attention to what is outputs exactly, it was taken like abstract, i need to take attribute of object using eval, because $str will be dynamic
@DanabekDuisekov I adjusted my answer for eval usage, but I would really advise against using it. (even the php docs tell us so.)

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.