php - Get variable based on value of another variable -


assume have object 3 properties:

protected $validmainstatements; protected $validprimarystatements; protected $validsecondarystatements; 

and got following method:

public function selecttype($stmt) {     $stmtparts = mainserverinterface::parse($stmt);     $type = $stmtparts[0] //returns either main, primary or secondary } 

depending on value of type, want use associated property. simple implementation be:

public function selecttype($stmt) {     $stmtparts = mainserverinterface::parse($stmt);     $type = $stmtparts[0] //returns either main, primary or secondary      if($type === "main") {         $usedprop = $this->validmainstatements;     } elseif($type === "primary") {         $usedprop = $this->validprimarystatements;     } elseif($type === "secondary") {         $usedprop = $this->validsecondarystatements;     } } 

i think don't have mention ugly , uncomfortable use. there way implement in easier way? (pseudocode):

$usedprop = $"valid".$type."statements"; 

<?php class foo {     protected $validmainstatements = 1;     protected $validprimarystatements = 2;     protected $validsecondarystatements = 3;      public function bar() {         $type = 'primary';          return $this->{'valid'.$type.'statements'};     } }  $foo = new foo; echo $foo->bar(); 

see variable variables - example #1 variable property example

-- edit , btw: i'd rather way:

<?php class foo {     protected $validstatements = [         'main' => 1,         'primary' => 2,         'secondary' => 3     ];      public function bar() {         $type = 'primary';          return $this->validstatements[$type];     } }  $foo = new foo; echo $foo->bar(); 

Comments

Popular posts from this blog

How to connect android app to App engine -

gcc - MinGW's ld cannot perform PE operations on non PE output file -

php - display validation error message next to the textbox in codeigniter -