将变量绑定到PHP中的超类

时间:2013-04-27 07:41:41

标签: php

所以我有两个班级:

table.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/

2 个答案:

答案 0 :(得分:1)

foreach bind $this->key = $value您使用$this->{$key} = $value代替{{1}}。

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

答案 1 :(得分:0)

  

它应该输出:

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

$objectVars = get_object_vars($user);