php - Class constructor creates new class fields with variable names? -


i'm trying initialize class through constructor php 5.5.13 getting weird results. setup this:

class foo{      public $bar;      public $top;      public $bot = array();       function __construct($bar, $top){         $this->$bar = $bar;         $this->$top = $top;      } }  $phonebook = array(); $user_input = $_post['query']; if(/* regex match */){    foreach($valid_input[0] $arr){       $name_and_number = explode(" ", $arr);       $phonebook[] = new foo($name_and_number[0], (int) $name_and_number[1]); //e.g. bob, 123       var_dump($phonebook[count($phonebook)-1]);    } } 

the weird part now, phonebook's var_dump returns:

object(foo)#1 (5) { ["bar"]=> null ["top"]=> null ["bot"]=> array(0) { }  ["bob"]=> string(3) "bob" ["123"]=> int(123) } 

running:

echo "$phonebook[0]->$bar"; echo "$phonebook[0]['bob']"; //since bob field apparently exists? echo "$phonebook[0]->$bob";  //just test if maybe $bob variable has been declared? 

all return empty page. i'm @ loss here. constructor setup weird? or way try access variables?

what need rid of second $ sign so

class foo{      public $bar;      public $top;      public $bot = array();       function __construct($bar, $top){         $this->bar = $bar;         $this->top = $top;      } } 

the reason why you're seeing 'weird' results because value of $bar , $top evaluated dynamically , used create new named property. resulting, in case, property named 'bob' , '123'


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -