php oop is there way to automatically set this var

2019-03-03 16:41发布

class User extends DatabaseObject {

    protected static $table_name='users';
    protected static $db_fields = array();

public  function __construct() {

    // Get columns from table
    global $database;
    $result_set = $database->query("SELECT * FROM ".self::$table_name." LIMIT 1");
    $num_fields = mysql_num_fields($result_set);
    for($i=0; $i<$num_fields; $i++) {
        $column_name = mysql_field_name($result_set, $i);
        // Set column names as variables
        self::$db_fields[] = $column_name; // THIS WORKS
    $this->{$column_name}; // THIS IS PROBLEMATIC!

  }

}

for example this $name = pulic $wherever; so I can call, for example, wherever->wherever;

so that I don't have to type this name every time I add the variables

public $md5;
public $credit;
public $pontaria_time;
public $Credits;
public $airoplayne;
public $city_id;
public $prisao_time;
public $crime2;
public $banck_time;

标签: php oop
3条回答
小情绪 Triste *
2楼-- · 2019-03-03 17:14

I think I don't understand your question, but I think you want to use the references operator:

class MyClass {
    protected $name;

    public myfunction() {
        $foo = $this->name;
        $this->name = &$foo;
        // now $foo is a reference to $this->name
    }
}
查看更多
▲ chillily
3楼-- · 2019-03-03 17:22

Um... I think you're asking how to not have to explicitly declare properties. In that case do this:

for($i=0; $i<$num_fields; $i++) {
    $column_name = mysql_field_name($result_set, $i);   
    $this->$column_name =  "";
  }

That will add all the column names as properties to your class, by default as public. Then you can access them using $this->md5, $this->credit, etc...

You should probably look at PDO and returning rows and object and applying a cast to it... PDO has fetch methods where you specify a classname and does this sort of thing automagically. I highly recommend NOT creating your own database abstraction library or ORM as there are already very good ones.

查看更多
做自己的国王
4楼-- · 2019-03-03 17:36
 $this->{$column_name}; // THIS IS PROBLEMATIC!

You need to use

$this->$column_name = $column_value

OR you can write all columns in $db_fields field and add

public function __get($name) {}

(read about magic methods)

查看更多
登录 后发表回答