Link to home
Start Free TrialLog in
Avatar of hankknight
hankknightFlag for Canada

asked on

How do I "exicute" a variable?

Hello.

How do I "exicute" a variable?

$code = "echo('Hello World');"

Avatar of Roonaan
Roonaan
Flag of Netherlands image

hankknight,

ob_start();
// execute code

$code = ob_get_clean();


Kind regards,

-r-
define execute,

cause you can't quite execute a variable,

variables store information,

you can execute a function

function myFirstFunction() {
     $var = "Hello World";
     echo $var;
}

myFirstFunction();
///this will output hello world to the screen

or

function myFirstFunction() {
     $var = "Hello World";
     return $var;
}

$var = myFirstFunction();

////This will return the variable in the function to your global variable.

Although this a simple demonstration, if there were a series of complex instructions in the function the output is all that would be returned
Avatar of hankknight

ASKER

If $code = "echo('Hello World');" then I want this to be done:
echo('Hello World')

If $code = "include('file.php');" then I want this to be done:
include('file.php');
$code = "echo('Hello World');"
exec($code);

http://us2.php.net/manual/en/function.exec.php
ASKER CERTIFIED SOLUTION
Avatar of Roonaan
Roonaan
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
exec() is for executing external commands that exist on the server.

Why do you want it to work that way, what are you trying to achieve?

I don't think it can work that way.
$variables are either
Integer,
String,
Boolen,
Arrays,
or Objects.

functions are executables
create functions like

function myEcho ($var) {
     echo $var;
}

then all you do is type
myEcho("hello World");
 and it will print it to the screen,

or create and include function,

function myInclude($var) {
    include($var);
}

then all you do is type,

myInclude("page.php");

and it will include it,

but these are all predefined executables in PHP,

So What are you trying to achieve and don't just say, trying to execute a variable, because you can't.
They're exactly right, my bad, sorry ... eval() is the one you want, not exec().

http://us2.php.net/manual/en/function.eval.php

$code = "echo('Hello World');"
eval($code);
so what about the if statement? something like this?

<?php
if($code == "echo('Hello World');")
    eval($code);

if($code == "include('file.php');")
    eval($code);
?>

Hope this helps.
nizsmo, I don't quite understand why you want if statements.  eval() will execute whatever statement is in $code, so it shouldn't be necessary to check what that is.  Am I missing something?