php - Looping through an array to create class properties -


i trying create class properties each element in array. array created @ point, i'm creating here demonstration purposes.

i'm not familiar classes , objects. me out?

class myclass   {    $days['first'] = "mon";  $days['second'] = "tue";  $days['third'] = "wed";   foreach ($days $k => $v) {      public $k = $v;  }  }    $obj = new myclass;    echo $obj->first; // mon 

i keep getting "parse error: syntax error, unexpected t_variable, expecting t_function".

use constructor set properties dynamically using $this->$key array passed in parameter, so:

class myclass   {       function __construct( $dates) {         foreach( $dates $k => $v)              $this->$k = $v;     } }  // can put __construct() function $days = array(); $days['first'] = "mon"; $days['second'] = "tue"; $days['third'] = "wed";  $obj = new myclass( $days); echo $obj->first; 

$this->$k type of variable-variables can set name of variable using value of variable.


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -