Run php code within a variable

Asked

Viewed 861 times

2

Good evening, everyone

There is the possibility to rotate this:

<?php

$variavel = 'foreach($v1 as $v2){echo $v2;};';

echo $variavel;

?>

Or is there any way to run a class within a variable (a Function I know has):

<?php
$variavel = 'class teste(){function oi(){echo 'oi';}}';
echo $variavel->teste->oi();
?>

something like.

Thank you in advance

  • 1

    Just one question, what’s the point of this?

  • Is a template engine or will run a stored code block?

  • Good morning buddy, the goal of this is for the following: I use Doctrine ORM, so I have all tables and fields in my database mapped into classes. Only if I wanted I had an idea of the client being able to add more fields in the table. The cool thing is that the default fields (fields written directly in the php file) cannot be deleted, it can only delete the fields (variables and gets and sets) that it created. Do you understand? A hug

  • Papa Charlie, regarding the template engine, I will use for this too. I did not know how to give the name to my creation! srsrsrsr I didn’t know it was called template engine! But I was happy to know that my idea does not exist in operation yet. Thank you friend. Hug

3 answers

1

Use the function val(). I just saw this possibility also with this function. Hugs!

1

<?php 
$clazz = "class teste(){function oi(){echo 'oi';}}"; 

eval($clazz); 

$variavel = new teste; 

echo $variavel->show();

$variavel->show(); 
?>

Try this.

  • Cool brother!! Thank you very much!! One more question, because I can’t create a variable inside: $clazz = "class teste(){ public $hi; function oi(){echo 'oi';}}";

  • I found it here, thanks: <?php &#xA;$clazz = "class SomeClass { var \$value = 'somevalue'; function show() { echo get_class(\$this);}}"; &#xA;&#xA;eval($clazz); &#xA;&#xA;$instance = new SomeClass; &#xA;&#xA;// Here output 'somevalue'; &#xA;echo $instance->value; &#xA;&#xA;echo "<br>"; &#xA;&#xA;//Here output 'someclass' &#xA;$instance->show(); &#xA;?> Source: [http://php.net/manual/en/function.eval.php#46382]

  • 1

    remember that "Eval is the root of all evil"

  • I’m on, I’ve been reading about it already! Thank you

0

The first case can be done as follows:

$funcao = function($variaveis) {
    foreach ($vriaveis as $variavel) {
        echo $variavel . PHP_EOL;
    }
}

$valores = [ 1, 2, 3 ];
$funcao($valores);

The second case is possible to do with PHP 7 using anonymous classes:

$classe = new class {
    public function oi() {
        echo 'oi' . PHP_EOL;
    }
}

$classe->oi();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.