Just as Tiago Luz replied, eval
would do well for you, since you are treating the string to only receive allowed characters and I believe you create the string yourself with the objects, right?
An example with eval
would look something like this.
<?php
class Expressao {
private $val;
private $nu1;
private $nu2;
private $ope;
function __construct($nu1, $ope, $nu2) {
$this->nu1 = $nu1;
$this->ope = $ope;
$this->nu2 = $nu2;
}
};
class Numero {
private $val;
function __construct($val) {$this->val = $val;}
};
class Operador {
private $val;
function __construct($val) {$this->val = $val;}
};
$exp = "new Expressao(
new Expressao(new Numero(10),new Operador('-'),new Numero(9)),
new Operador('+'),
new Expressao(new Numero(7), new Operador('-'),new Numero(6))
)";
$r = eval('return ('.$exp.');');
var_dump($r);
Note that I concatenate a return
with the expression, this is so that the variable $r
receives the result of the expression and not only that it is executed. It is as if eval
throws your code inside a function and executes, so to receive something from this function you need to give return
.
I hope it has become clear.
I still recommend that you do all this parser in class Expressao
, something like
$exp = new Expressao('(10-9)+(7-6)');
And in there you create a function that treats the string "(10-9)+(7-6)"
and turns it into your objects.
You can also create "dynamic" objects, for example:
function getObj($val) {
if (in_array($val, explode('', '(+-)'))) {
$class = 'Operador';
} else if (preg_match('/^[0-9]+$/', $val) > 0) {
$class = 'Numero';
} else return null;
return new $class($val);
}
But I'm not having the time to work out this code ↑