假设我有一个具有3个属性的对象:
protected $validMainStatements;
protected $validPrimaryStatements;
protected $validSecondaryStatements;
我得到了以下方法:
public function selectType($stmt) {
$stmtParts = MainServerInterface::parse($stmt);
$type = $stmtParts[0] //returns either Main, Primary or Secondary
}
根据type
的值,我想使用关联的属性。一个简单的实现是:
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;
}
}
我想我不必提及使用它是丑陋和不舒服的。有没有办法以更简单的方式实现这一点?像(伪代码)的东西:
$usedProp = $"valid".$type."Statements";
答案 0 :(得分:3)
<?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();
请参阅Variable variables - Example #1 Variable property example
- 编辑和顺便说一下: 我宁愿这样做:
<?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();
答案 1 :(得分:1)
尝试以下
$usedProp = $this->{"valid".$type."Statements"};
<强>测试强>
<?php
class test {
public $validMainStatements = 'hello';
}
$instance = new test;
$type = 'Main';
echo $instance->{"valid".$type."Statements"};
?>
<强>结果强>
hello
答案 2 :(得分:0)
只需使用variable variables。
$variableName = 'valid'.$type.'Statements';
$this->{$variableName};