I really want to know any better way to turn the column name as property name without assigning any value and i also want to make the id column private or protected so that nobody cann't access it.
It's a simple thing I want to do. I just grab all the column name from a database table and want to turn the column name as class property. see the code and comment below:
<?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;