Home > Back-end >  Execute method in class dynamic using PHP 7.4
Execute method in class dynamic using PHP 7.4

Time:05-21

I would like to know how I can dynamically execute a method in my class using the following string.

$model = "Shop\Cart\Models\Cart@getInfo";

my idea is to save this command in the database, and then dynamically call the command and get the data return..

My difficulty is how to execute this command, is it possible?

An alternative I did is to explode the @ and then use the call_user_func method, but I would like to know if there is any way without using explodes and making the request directly.

CodePudding user response:

Define classname first

$className = 'Shop\Cart\Models\Cart';

Then call the method

(new $className())->getInfo();

CodePudding user response:

You can make a function which can extract class and method name and call afterwards.

<?php
$model = "Cart@getInfo";

function make($str) {
    $a = explode("@", $str);
    $c = new $a[0];
    
    return $c->{$a[1]}();
}


class Cart {
    public function getInfo() {
        return "Hello World";
    }
}


$res = make($model);
print_r($res);

output

// Hello World

CodePudding user response:

Try to use eval()

<?php
require_once './Classes/MyClasses.php';
function e($string)
{
    $string = str_replace('@', '::', $string);
    return eval($string . '();');
}
$a = e('Classes\MyClasses\MyClass@test'); // test
?>

file ./Classes/MyClasses.php contains next:

<?php
namespace Classes\MyClasses;
class MyClass
{
    public static function test()
    {
        echo 'test';
    }
}
?>
  •  Tags:  
  • php
  • Related