1

I'm just wondering on how I'd be able to use PHP coding in PHP variables? So for example. I want something like

$Start = " IF($lala == "0"){ echo '";
$End = " '; }";

and to be able to use it as

echo ''.$start.' hello '.End.'';

It may sound weird, but I'd like it to be done in a similar way to this.

Thank you

11
  • 4
    Why do you want to do this? Commented Mar 17, 2016 at 13:00
  • 5
    I guess this will help you: php.net/manual/en/function.eval.php Commented Mar 17, 2016 at 13:00
  • 2
    $start != $Start, and End != $End Commented Mar 17, 2016 at 13:01
  • 1
    This is such a humugously bad idea! Commented Mar 17, 2016 at 13:08
  • 4
    Why not use a function? What you described is the exact use case for a function. Commented Mar 17, 2016 at 13:10

3 Answers 3

1

I can't even begin to tell you how dangerous executing code from a string is. So don't even think about it...

Instead use a function or a Closure (once you feel somewhat safe with PHP)

<?php
function myFunction($str) {
  $lala = lalaFunction();
  if ($lala) { return $str; }
}

And then just call:

echo myFunction('something');
Sign up to request clarification or add additional context in comments.

1 Comment

This is absolutely the way to go! Do NOT use eval ().
0

Yes, you can by using eval():

<?php
    $lala = 0;
    $Start = "if($lala == '0'){ echo ";
    $End = ";}";
    eval($Start.'hello'.$End);
?> 

output:

hello

Comments

0

in that case for if condition you can simply write the code like this:

<?php
$check=0;
$x='true';
$y='false';
$value=$check==0?$y:$x;
?>

in this $check==0 is used for if AND ? is used for the event to run if condition passed is true and : is used for else part.

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.