Dynamically create PHP object based on string

前端 未结 5 2285
不思量自难忘°
不思量自难忘° 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:24

    But know of no way to dynamically create a type based on a string. How does one do this?

    You can do it quite easily and naturally:

    $type = 'myclass';
    
    $instance = new $type;
    

    If your query is returning an associative array, you can assign properties using similar syntax:

    // build object
    $type = $row['type'];
    $instance = new $type;
    
    // remove 'type' so we don't set $instance->type = 'foo' or 'bar'
    unset($row['type']);  
    
    // assign properties
    foreach ($row as $property => $value) {
       $instance->$property = $value;
    }
    

提交回复
热议问题