Dynamically create PHP object based on string

前端 未结 5 2286
不思量自难忘°
不思量自难忘° 2020-11-27 15:17

I would like to create an object in PHP based on a type defined by a string in a MySQL database. The database table has columns and sample data of:



        
5条回答
  •  孤城傲影
    2020-11-27 15:46

    There's a very neat syntax you can use that I learned about a couple of months ago that does not rely on a temporary variable. Here's an example where I use a POST variable to load a specific class:

    $eb = new ${!${''} = $_POST['entity'] . 'Binding'}();
    

    In your specific case though, you would be able to solve it by using PDO. It has a fetch mode that allows the first column's value to be the class the row instantiates into.

    $sth->fetch(PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE);
    

提交回复
热议问题