php - 想在 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;
解决方案
我看不出你的问题的重点。评估价值有什么不好?您甚至可以分配一个 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
)
所以它似乎正是你想要的。
推荐阅读
- python - 如何从 python 的 for 循环中打印特定项目?
- python - numpy array prod vs 乘以列表项
- python - 为什么会出现“IndexError:字符串索引超出范围”?
- google-play - 以前版本的应用程序需要多长时间才能更新到在 goolge play 商店推出的新版本?
- fish - 在 Fish 的同一行中使用 eval 和后台进程
- java - 如何连续扫描输入到控制台?
- r - 将ggplot2转换为ggplotly时缺少geom_rect
- git - 从 master 合并到分支后 git 会做什么?
- google-cloud-platform - openstack4j 向错误的主机发送请求
- javascript - 使用车把从 Dark Sky API 获取数据,路由问题