Reputation: 3953
Assume I have an object with 3 properties:
protected $validMainStatements;
protected $validPrimaryStatements;
protected $validSecondaryStatements;
And I got the following method:
public function selectType($stmt) {
$stmtParts = MainServerInterface::parse($stmt);
$type = $stmtParts[0] //returns either Main, Primary or Secondary
}
Depending on the value of type
, I want to use the associated property. A simple implementation would 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 I don't have to mention that this is ugly and uncomfortable to use. Is there a way to implement this in an easier way? Something like (pseudocode):
$usedProp = $"valid".$type."Statements";
Upvotes: 0
Views: 68
Reputation: 16997
Try like below
$usedProp = $this->{"valid".$type."Statements"};
Test
<?php
class test {
public $validMainStatements = 'hello';
}
$instance = new test;
$type = 'Main';
echo $instance->{"valid".$type."Statements"};
?>
Result
hello
Upvotes: 1
Reputation: 9123
Just use variable variables.
$variableName = 'valid'.$type.'Statements';
$this->{$variableName};
Upvotes: 0
Reputation: 96159
<?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 and btw: I'd rather do it this 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();
Upvotes: 3