Do not use eval
! The eval
function can have unwanted side effects on your code and is often a security vulnerability.
For this purpose you can use PHPs own serialization. Have a look at the following example.
<?php
declare(strict_types=1);
namespace Marcel;
class MyTest
{
protected string $something;
public function __construct(string $something)
{
$this->something = $something;
}
public function getSomething(): string
{
return $this->something;
}
}
$object = new MyTest('Marcel');
// the $serialized var contains a string representing the initialized class
// the string can be stored in the database
$serialized = serialize($object);
var_dump($serialized);
// when you query from database, just unserialized the queried string
$unserialized = unserialize($serialized);
var_dump($unserialized->getSomething());
As you said in the comments, you don 't know the classname. Well, I better don 't ask, what the hell you 're trying to do. Anyway ... here 's a short example using eval()
.
<?php
declare(strict_types=1);
namespace Marcel;
use ParseError;
$string = 'class MyTest
{
protected string $something;
public function __construct(string $something)
{
$this->something = $something;
}
public function getSomething(): string
{
return $this->something;
}
}';
try {
$before = get_declared_classes();
ob_start();
eval($string);
$class = ob_get_contents();
ob_end_clean();
$classname = current(array_diff(get_declared_classes(), $before));
$object = new $classname('Marcel');
var_dump($object->getSomething());
} catch (ParseError $error) {
var_dump($error);
}
This example compares the declared classes before and after eval execution. The name of the class comes from the difference between the two arrays. With the computed name you can initialize the class.
Beware! This example does not cover all possibilities. There are some more things to note.
- What about constructor parameters?
- How do you know which methods the class contains?
- You 're running into problems, if there are more than one class definition in the eval'd code.
- What about error handling?
- You will run into serious problems when it comes to dealing with namespaces
Most of the questions you can solve with the PHP Reflection API.
Again: Your plan is highly risky and you should not do this in a real world application.