-2

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;
  • Possible duplicate of: [How to convert an array to object in php](https://stackoverflow.com/questions/1869091/how-to-convert-an-array-to-object-in-php) –  Jul 28 '18 at 06:44
  • Possible duplicate of [How to convert an array to object in PHP?](https://stackoverflow.com/questions/1869091/how-to-convert-an-array-to-object-in-php) –  Jul 28 '18 at 06:44

1 Answers1

0

I fail to see the point of your question. What is so bad about assinging a value? You can even assign a NULL value as you showed. This is the same as assigning no value. You can read that here:

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

I tested the NULL value like this:

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>';

This returns:

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

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

So it seems to do exactly what you want.

KIKO Software
  • 15,283
  • 3
  • 18
  • 33