首页 > 解决方案 > 想在 php 中将数据库列名作为类属性

问题描述

我真的很想知道任何更好的方法将列名转换为属性名而不分配任何值,并且我还想将id列设为私有或受保护,这样任何人都无法访问它。

这是我想做的一件简单的事情。我只是从数据库表中获取所有列名,并希望将列名转换为类属性。请参阅下面的代码和评论:

<?php
// grab all the table column name from database
$query = "SHOW COLUMNS FROM test_table";
$result = mysqli_query($connection, $query);
$column_array = mysqli_fetch_all($result, MYSQLI_ASSOC);
print_r($column_array); // result below
/*
  Array (
     [0] => Array (
        [Field] => id        // column name
        [Type] => int(11)
        [Null] => NO
        [Key] => PRI
        [Default] =>
        [Extra] => auto_increment
     )

     [1] => Array (
        [Field] => name      // column name
        [Type] => varchar(50)
        [Null] => NO
        [Key] =>
        [Default] =>
        [Extra] =>
     )
  )
*/
//turn the column name as class property name
class ExampleClass {
public function __construct() {
  global $column_array;
    for ($loop = 0; $loop < count($column_array); $loop++) {
       $column_name = $column_array[$loop]["Field"];
       $this->$column_name = null; // yes i can do this but i have to assign the value
       public $$column_name; // cannot do this
       var $$column_name; // cannot do this also
    }
  }
}
$obj = new ExampleClass;

标签: phpoop

解决方案


我看不出你的问题的重点。评估价值有什么不好?您甚至可以分配一个 NULL 值,如您所展示的。这与不赋值相同。你可以在这里阅读:

http://php.net/manual/en/language.types.null.php

我像这样测试了NULL值:

class Test {
  private $a = 1;
  private $b;

  public function test() {
    return print_r(get_object_vars($this),TRUE);
  }
}

$test = new Test;

echo '<pre>'.$test->test().'</pre>';

$test->c = NULL;
$test->d = 2;

echo '<pre>'.$test->test().'</pre>';

这将返回:

Array
(
    [a] => 1
    [b] => 
)

Array
(
    [a] => 1
    [b] => 
    [c] => 
    [d] => 2
)

所以它似乎正是你想要的。


推荐阅读