Please look at the code, the array contains the table field names of the table
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;
}
The idea is to remove the public variables with a function so that it automatically creates public variable from the array which i can access ---
Example
I want to remove the
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
section, and want this to be automatically generated by the $db_fields array.
So that I can access the objects by
$user = new User();
$user->username = "Ismail";
What I did was
extract($db_fields);
but it gives an error:
Parse error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION in C:\xampp\htdocs\advphp\dbclass\extractex.php on line 3
unfortunately your idea does not work
if you try to use extract($db_fields); it's a method it need to run from inside a method
something like a constructor or a function. extract($db_fields); it will extract the variables for you but they wont be public they will be local to that function for example if you try this
function __construct(){
extract($db_fields);
// the $id will be available in the constructor only
// it will get disposed when this method finished executing
}
another approach is to use a property or setter and getter approach
<?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');
?>
you can test the codes here http://codepad.org/8MwBwdut
You could remove $db_fields all together and depend on the columns returned by your SQL query like so:
class User
{
private $_data;
public function __construct($id = null) {
//TODO: Load data into $this->_data for user of $id
}
public function __get($name) {
if (array_key_exists($name, $this->_data))
return $this->_data[$name];
return NULL;
}
public function __set($name, $value) {
$this->_data[$name] = $value;
}
public function UpdateUser(){
//TODO: update the database with any changes to the user data or do an insert for new user
}
}
and then you can get/set properties dynamically without needing to first declare them like so:
$newUser = new User();
$newUser->username = "Ismail";
$newUser->UpdateUser();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With