How to transform a string into an object?

Asked

Viewed 1,152 times

2

I have the following String:

$exp = "(10-9)+(7-6)";

Let’s say I process this String and can return the following result, in the format String:

$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))
)";

How do I dynamically create an object Expressao as indicated in String?

  • You want to parse in php eh?

  • @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

4 answers

3


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

  • Exactly what I was looking for

  • Cool! I hadn’t seen your answer.

0

You can do this with the function eval($code) php.

Whatever is in $code will be executed as if it were PHP code. Beware of possible security breaches!

At this link is the explanation.

  • I was already imagining that it would be Eval(), but I do not know how to use this function. There is an example in said link that helps to solve my problem

  • In the code there is a function that sanitizes the input string allowing only numbers and ( - + ) I believe that there are no greater risks with Eval() anyway it is only an exercise of OO

  • The Eval($bla) function executes the php code that is in the $bla variable, as if it were written in your script. Example: Eval("echo 'hi';");

  • James Light, you could formulate a response, why can’t I perform this operation with Oil(). I get the error message: eval()'d code on line 1

0

As a matter of curiosity

Researching I managed to find a way to do what eval() create the object as you wanted using a closure

public function criaObjeto($obj){
        eval("\$newObj = function(){return $obj;};");
        return $newObj();
}

I don’t have complete mastery of how to work with eval() to state whether it does not generate a security breach.

In my code I put a function that sanitizes data entry allowing only caracteres numéricos, ( , ) , + and -.

class Validacao{
    private function limpaString($obj){
        return preg_replace("/[^0-9\+\-\(\)]/", "", $obj);
    }
}

However, I’m not entirely sure about security

-2

The proper thing would be for you to do it this way:

$ExpressaoObj->new Expressao();

It’s just that your code is very confused and wrong!

Browser other questions tagged

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