phpphp-parse-error

Make PHP database class generic by Generating dynamic variables


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


Solution

  • 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