Just as James Light answered, eval
would do well in your case, since you are handling the string to receive only allowed characters and believe that you create the string with the objects yourself, right?
An example with the 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 grant one return
with the expression, this is for the variable $r
receives the result of the expression and not just that it is executed. It is as if the eval
played your code within a function and executed, so to receive something from this function you need to give a return
.
I hope that’s clear.
I still recommend 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 handles the string "(10-9)+(7-6)"
and turn 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 don’t have time right now to draw up that code
You want to parse in php eh?
– fernandoandrade
@fernandoandrade I’m doing a function that receives a numeric expression and transforms it into an object. I was able to treat the string and mount it as accurate, but the result is a string I cannot execute. I want to execute what is in this string and thus create an expression() object with the given attributes
– Rúbio Falcão