class User {
public $db_fields = array('id', 'username', 'password', 'first_name', 'last_name');
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
}
function __construct(){
extract($db_fields);
// the $id will be available in the constructor only
// it will get disposed when this method finished executing
}
另一种方法是使用属性或 setter 和 getter 方法
<?php
class User {
private $db_fields = array(
'id',
'username',
'password' => 'ismailPassword',
'first_name',
'last_name'
);
function getValue($key){
if (array_key_exists($key, $this->db_fields)){
return $this->db_fields[$key];
}
return NULL;
}
function setValue($key, $value){
$this->db_fields[$key] = $value;
}
}
$user = new User();
$user->setValue('username', 'Ismail');
echo " Username: ";
echo $user->getValue('username');
echo "\n\n Password: ";
echo $user->getValue('password');
?>