Php 根据另一个变量的值获取变量

Php 根据另一个变量的值获取变量,php,Php,假设我有一个具有3个属性的对象: protected $validMainStatements; protected $validPrimaryStatements; protected $validSecondaryStatements; 我得到了以下方法: public function selectType($stmt) { $stmtParts = MainServerInterface::parse($stmt); $type = $stmtParts[0] //re

假设我有一个具有3个属性的对象:

protected $validMainStatements;
protected $validPrimaryStatements;
protected $validSecondaryStatements;
我得到了以下方法:

public function selectType($stmt) {
    $stmtParts = MainServerInterface::parse($stmt);
    $type = $stmtParts[0] //returns either Main, Primary or Secondary
}
根据
类型
的值,我希望使用关联的属性。一个简单的实施方案是:

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 = $this->{"valid".$type."Statements"};
测试

<?php

   class test {
         public $validMainStatements = 'hello';
   }

  $instance = new test;

  $type = 'Main'; 
  echo $instance->{"valid".$type."Statements"};

?>
hello

试试下面这样

$usedProp = $this->{"valid".$type."Statements"};
测试

<?php

   class test {
         public $validMainStatements = 'hello';
   }

  $instance = new test;

  $type = 'Main'; 
  echo $instance->{"valid".$type."Statements"};

?>
hello
就用吧

就用吧


有效的
语句
(在
echo
语句中
{}
内的语句)需要用引号括起来!,还有你的欢迎:)@someOne:谢谢,现在按照你的建议编辑,但我不明白为什么我没有在eval.in/中得到错误,请看demo@someOne当然,依赖假定的字符串是非常危险的-总是用
最有可能是因为eval.in已关闭警告并使用最新版本的PHP(具有做出假设的功能)!!
有效的
语句
(在
echo
语句中
{}
内的语句)需要用引号括起来!,还有你的欢迎:)@someOne:谢谢,现在按照你的建议编辑,但我不明白为什么我没有在eval.in/中得到错误,请看demo@someOne当然,依赖假定的字符串是非常危险的-总是用
最有可能是因为eval.in已关闭警告并使用最新版本的PHP(具有做出假设的功能)!!好吧,我喜欢你的第二个解决方案,真的很优雅。出售。谢谢。好吧,我喜欢你的第二个解决方案,真的很优雅。出售。非常感谢。
$variableName = 'valid'.$type.'Statements';
$this->{$variableName};