我想两个不同的PHP代码转化成一个单一的PHP tag.This可能听起来有点不可思议,但最近我发现了这样的问题,并以正确的标记回答。
我无法找到我目前失去了地址。
我的问题:
例如;
$gates = array('t1','t2','t3',t4','t5');
$openGates->
和$gates
合并。
结果:
$openGates->t1;
或T2,T3。
如果我没有记错,答案我发现之前是问题;
$openGates->{$gates};
这样。我不确定
我怎样才能做到这一点?
你似乎是与阵列混乱的对象。数组只包含数据,除非你有钥匙也创造了他们。如:
$gates = array('t1'=>true,'t2'=>false,'t3'=>"maybe",'t4'=>0,'t5'=>50);
马修·佩奇是正确的,你应该查找PHP OOP一个解决方案。
话虽这么说,你可以投你的数组对象只要具有键和值:
$gates = (object) array('t1'=>true,'t2'=>false,'t3'=>"maybe",'t4'=>0,'t5'=>50);
要么
$openGates = (object) $gates;
这将允许你访问你已经证明的方式,对象的“属性”:
echo $openGates->t1;
,例如。的操作者->
只适用于对象,这是类,而不是阵列实例。
如果你投你的数组对象的类型,请确保您有两个键和值。
这不是简单的为新手程序员...
首先:
$gates = array('t1','t2','t3','t4','t5');
这阵
$openGates->
这是类实例。顺便说一句。您可以检索类实例VAR像$className->varName
你不能简单合并阵列和类实例。但是你可以通过循环创建新类的实例变量。
foreach($gates as $gateKey=>$gateVal) {
$openGates->$gatesVal = NULL;
}
但我认为这是在结果应该是这样的:
$gates = array('t1'=>'opened','t2'=>'closed','t3'=>'closed','t4'=>'opened','t5'=>'opened');
foreach($gates as $gateKey=>$gateVal) {
$openGates->$gateKey = $gateVal;
}
echo $openGates->t1;
// or
foreach($gates as $key=>$val) {
echo $openGates->$key.PHP_EOL;
}
顺便说一句,你可以简单的设置$openGates->gates = $gates;
并调用它像echo $openGates->gates['t1'];