Variabili variabili di puntamento per array o oggetti nidificati
-
19-09-2019 - |
Domanda
E 'possibile creare una variabile che punta variabile per un array o di oggetti nidificati? La documentazione php specificamente dice che non può puntare a superglobals ma il suo poco chiaro (almeno per me) se questo vale per gli array in generale.
Ecco il mio tentativo per l'array var var.
// Array Example
$arrayTest = array('value0', 'value1');
${arrayVarTest} = 'arrayTest[1]';
// This returns the correct 'value1'
echo $arrayTest[1];
// This returns null
echo ${$arrayVarTest};
Ecco qualche semplice codice per mostrare cosa intendo per oggetto var var.
${OBJVarVar} = 'classObj->obj';
// This should return the values of $classObj->obj but it will return null
var_dump(${$OBJVarVar});
Mi sto perdendo qualcosa di ovvio qui?
Soluzione
Array approccio elemento :
- nome di matrice estratto dalla stringa e conservarla in
$arrayName
. - indice di matrice estratto dalla stringa e memorizzarlo in
$arrayIndex
. - Analizzare in modo corretto anziché nel suo complesso.
Il codice:
$arrayTest = array('value0', 'value1');
$variableArrayElement = 'arrayTest[1]';
$arrayName = substr($variableArrayElement,0,strpos($variableArrayElement,'['));
$arrayIndex = preg_replace('/[^\d\s]/', '',$variableArrayElement);
// This returns the correct 'value1'
echo ${$arrayName}[$arrayIndex];
Proprietà dell'oggetto avvicinano :
- esplodere la stringa che contiene la classe e la proprietà che si desidera accedere dal suo delimitatore. (->)
- Assegna queste due variabili per
$class
e$property
. - separatamente anziché come un tutto sulla
var_dump()
Parse
Il codice:
$variableObjectProperty = "classObj->obj";
list($class,$property) = explode("->",$variableObjectProperty);
// This now return the values of $classObj->obj
var_dump(${$class}->{$property});
Funziona!
Altri suggerimenti
Usa = &
assegnare per riferimento:
$arrayTest = array('value0', 'value1');
$arrayVarTest = &$arrayTest[1];
$arrayTest[1] = 'newvalue1'; // to test if it's really passed by reference
print $arrayVarTest;
In echo $arrayTest[1];
nome vars è $arrayTest
con un indice di array di 1
, e non $arrayTest[1]
. Le staffe sono PHP "parole chiave". Stessa cosa con il metodo di notazione e l'operatore ->
. Quindi, è necessario dividere.
// bla[1]
$arr = 'bla';
$idx = 1;
echo $arr[$idx];
// foo->bar
$obj = 'foo';
$method = 'bar';
echo $obj->$method;
Che cosa si vuole fare suona più come valutare il codice PHP (eval()
). Ma ricordate: eval è il male. ; -)
No, non è possibile farlo. Si può farlo solo con i nomi delle variabili, degli oggetti e delle funzioni.
Esempio:
$objvar = 'classObj';
var_dump(${$OBJVarVar}->var);
Alternative può avvenire tramite eval () o facendo pre-elaborazione.
$arrayTest = array('value0', 'value1');
$arrayVarTest = 'arrayTest[1]';
echo eval('return $'.$arrayVarTest.';');
eval('echo $'.$arrayVarTest.';');
Cioè, se sei molto sicuro di quello che sta per essere l'ingresso.
Per la pre-elaborazione:
function varvar($str){
if(strpos($str,'->') !== false){
$parts = explode('->',$str);
global ${$parts[0]};
return $parts[0]->$parts[1];
}elseif(strpos($str,'[') !== false && strpos($str,']') !== false){
$parts = explode('[',$str);
global ${$parts[0]};
$parts[1] = substr($parts[1],0,strlen($parts[1])-1);
return ${$parts[0]}[$parts[1]];
}else{
return false;
}
}
$arrayTest = array('value0', 'value1');
$test = 'arrayTest[1]';
echo varvar($test);