2013-04-27 76 views
0
一個超

所以,我有兩個類:綁定變量在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"=>"[email protected]");  
    $user->bind($data); 
    $classVars = get_class_vars(get_class($user)); 
    print_r($classVars); 

?> 

它應該返回:

Array(
    [username] => Forest, 
    [password] => *******, 
    [email]=>[email protected] 
    [table] => user 
) 

而是返回:

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/

+0

我非常嚴格地建議你改變你的密碼;) – Vyktor 2013-04-27 07:49:22

回答

1

foreachbind你使用$this->key = $value代替$this->{$key} = $value

而要獲取實例變量(不是類默認值),請使用get_object_vars()

+2

另外,'$ this - > $ key = $ value;'應該也是一樣的。 – 2013-04-27 08:04:24

0

它應該輸出:

不,它不應該。 get_class_vars回報在類中定義的變量,你正在尋找實例化對象的屬性,所以你應該使用:在

$objectVars = get_object_vars($user);