我真的想知道将列名转换为属性名而不分配任何值的更好方法,并且我还想将 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;
答案 0 :(得分:0)
我看不到你的问题的重点。追求价值有什么不好?您甚至可以按照显示的那样分配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
)
所以它似乎完全可以满足您的要求。