Dynamically create PHP object based on string

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

    as silkfire says, this can be achieved by using PDO specific modes, so here is an example. Using your same database values and defined objects:

     id | type | propertyVal
    ----+------+-------------
      1 | foo  | lorum
      2 | bar  | ipsum
    
    class ParentClass {...}
    class Foo extends ParentClass {private $id, $propertyVal; ...}
    class Bar extends ParentClass {private $id, $propertyVal; ...} 
    //...(more classes)...
    

    with a single query (you must name the field containing the class name first):

    $stmt = $db->prepare('SELECT type,id,propertyVal FROM table WHERE id=1');
    $stmt->execute();
    $foo = $stmt->fetch(PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE);
    var_dump($foo); // $foo is a newly created object of class foo, with properties named like and containing the value of subsequent fields
    

    this is cool but it gets cooler with a while

    $stmt = $db->prepare('SELECT type,id,propertyVal FROM table');
    $stmt->execute();
    while ($object = $stmt->fetch(PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE))
     {var_dump($object);} // here all desired objects, dynamically constructed accordingly to the first column returned by the query
    

    you can define a constructor (which will be called after the values from database are assigned to properties) to work on those dynamically assigned properties, say by replacing a string with it's uppercased value

    class foo
     {function __construct ()
       {$this->uper = strtoupper($this->propertyVal);}}
    

提交回复
热议问题