I have this function to fill my class vars. When there is a file to handle, handle_uploaded_files()
is called that return a comma separated file list name.
When i access the $this->image
the values are corrects ( "image(1).jpg,image(2).jpg,image(3).jpg,image(4).jpg"
), but when access the property outside the class, i receive a strange result: only commas, but no values between then ( ",,,"
).
public function fill_vars($array, $files = null) {
foreach(array_keys($array) as $key => $value) {
$this->$value = $array[$value];
if (!empty($files)) {
foreach ($files as $key => $value) {
$this->$key = handle_uploaded_files($files[$key]);
}
}
}
}
I have no idea what's going on. Any advices?
Sorry about my english.
Rename your variables in the inner foreach
-loop. You overwrite $key
and $value
from the outer loop.
There is no point in calling array_keys($array)
in the outer loop since $key becomes a numeric index of the key in the newly generated array. Instead you can write
foreach($array as $key => $value) {
$this->$key = $value;
/* ... */
}
This only works if $key
is a valid identifier. But that's no different than your code.
The inner loop can be rewritten as
$this->$key = handle_uploaded_files($value);
But you definitely should rename inner loop variables first.
After that you can check if $this->$key
from the inner loop should ever overwrite $this->$key
from the outer loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.