php - 通过生成动态变量使 PHP 数据库类通用

标签 php php-parse-error

<分区>

请看代码,数组包含表的表字段名

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;

}

我的想法是用一个函数删除公共(public)变量,以便它自动从我可以访问的数组中创建公共(public)变量---

示例

我要删除

public $id;
public $username;
public $password;
public $first_name;
public $last_name;

部分,并希望它由 $db_fields 数组自动生成。

这样我就可以访问对象了

$user = new User();
$user->username = "Ismail";

我做的是

extract($db_fields);

但它给出了一个错误:

Parse error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION in C:\xampp\htdocs\advphp\dbclass\extractex.php on line 3

最佳答案

不幸的是你的想法行不通 如果您尝试使用 extract($db_fields); 它是一种需要从方法内部运行的方法 类似于构造函数或函数。 extract($db_fields); 它将为您提取变量,但它们不会公开,它们将是该函数的本地变量,例如,如果您尝试此操作

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

你可以在这里测试代码 http://codepad.org/8MwBwdut

关于php - 通过生成动态变量使 PHP 数据库类通用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13890359/

相关文章:

php - SQL 查询值未传递给 PHP 对象

php - 如何使用 PHP 读取 json 属性

php - 解析错误: unexpected '@' symbol in constant function in php

php - 为什么 PHP 会抛出这个解析错误?

php - 尝试在函数中使用私有(private)变量时的错误代码

php - 从 MySQL 查询构建数组?

php - 本地运行 Magento

php - 在不刷新的情况下更新标签内的变量