How to enter PHP code from a database into a PHP script?

I want to save php code in my database and then use it in my script.

class A {
    public function getName() {
        return "lux";
    }
}
// instantiates a new A
$a = new A();

My database has data such as

"hello {$a->getName()}, how are you ?"

In my php code, I am loading data into the $ string variable

$string = load_data_from_db();
echo $string; // echoes hello {$a->getName()}, how are you ?

So now the line $ contains "hello {$ a-> getName ()}, how are you?"

{$ a-> getName ()} is still not interpreted

Question: I cannot find how to write the rest of the code so that {$ a-> getName ()} is interpreted "in hello lux, like you." Can anyone help?

$new_string = ??????
echo $new_string; //echoes hello lux, how are you ?

Is there a solution with eval ()? (please not debate about evil eval;)) Or any other solution?

+3
source share
4 answers

eval() - , ( phill, )

: , eval - :

eval('$string = "'.load_data_from_db().'";');

( , , )

+3

, - .

, sprintf

DB

"hello %s, how are you ?"

php-

$string = load_data_from_db();
echo sprintf($string,$a->getName()); // replaces %s with the function value.

($ a- > getName()) , (, A)

+3

, temp.file, include('temp.file');

0

NOT. /, .

"" .

:

class A {
    private $name;

    public function getName() {
        return $this->name;
    }

    public function setName($name) {
        $this->name = $name;
    }
}
// Query DB
// Don't know your query so just using what you have
$passed_name = load_data_from_db(); // This would return "lux"

// instantiates a new A
$a = new A();
$a->setName($passed_name);
echo "hello ".$a->getName().", how are you ?<br />\n";
0

Source: https://habr.com/ru/post/1749934/


All Articles