在PHP中将变量绑定到超类


Binding variables to a superclass in PHP

所以我有两个类:

表.class

<?php
    class table {
        protected $id = null;
        protected $table = null;
        function __construct() {
        }
        function bind($data) {
            // print_r($data);
            foreach ($data as $key=>$value) {
               $this->key = $value;
               //   echo $key."--".$value;
               //     echo $this->$key;
            }
        }
   }
?>

user.class

<?php
    class user extends table
    {
        var $username = null;
        var $password = null;
        var $email = null;
        var $table = "user";
    }
?>

我还有一个索引引导程序。。。。

<?php
    include('table.class.php');
    include('user.class.php');
    $user = new user();
    $data = array("username" => "Forest", "password" => "*****",  "email"=>"foo@bar.com");    
    $user->bind($data);
    $classVars = get_class_vars(get_class($user));
    print_r($classVars);
?>

它应该返回:

Array(
    [username] => Forest,
    [password] => *******,
    [email]=>foo@bar.com
    [table] => user
)

INSTEAD返回:

Array (
    [username] =>
    [password] =>
    [email] =>
    [table] => user
)

有人能告诉我为什么变量没有绑定到超类吗?????

根据这里它应该工作:

http://codeslayer2010.wordpress.com/2012/04/08/developer-journal-2012-03-30-building-a-php-database-connection-class-from-scratch-singleton-activerecord/

bindforeach中,您使用的是$this->key = $value而不是$this->{$key} = $value

要获取实例的变量(而不是类默认值(,请使用get_object_vars()

它应该输出:

不,不应该。get_class_vars返回类中定义的变量,您正在寻找实例化的对象属性,因此应该使用:

$objectVars = get_object_vars($user);