I am currently in the development of my Class in PHP. I have an array with values in it, and I would like to use the array fieldname as a $this reference. Let me show you what I got:
<?php
class Server {
private $playlist;
private $mp3;
private static $ressourceFolder;
private static $sudoUser;
And in my array it contains:
array(6) {
["playlist"]=>
int(8002)
["mp3"]=>
int(1024)
["ressourceFolder"]=>
bool(true)
["sudoUser"]=>
bool(true)
}
So I would like to use in my foreach something to get the value of the array field into the class global variable, the array fieldname is the same as the variable so this 'should' work, but it doesn't :(
foreach($ressourceArray as $ressourceField=>$ressourceValue) {
$this->$ressourceField = $ressourceValue;
}
I would really appreciate if someone could tell me why this can't work and how to make this 开发者_C百科'workable'...
Thanks in advance!
It does work, see Demo:
<?php
$array = array("playlist"=> 8002, "mp3"=>1024);
class Mix {
public function __construct($array) {
foreach($array as $key => $value) {
$this->$key = $value;
}
}
}
$class = new Mix($array);
var_dump($class);
It will assign new public members to the object $this
based on key/value pairs of the array.
Dealing with bad named keys in the array
If the keys contain values that are not valid variable names, it can be non-trivial to access the properties later ({property-name}
), see PHP curly brace syntax for member variable.
Casting the array to object before adding will help to prevent fatal errors for those key names that are completely invalid:
$object = (object) $array;
# iterate over object instead of array:
foreach($object as $key => $value) {
$this->$key = $value;
}
Those keys are just dropped by the cast.
You may get it working with the magic method __set
and __get
. See: http://php.net/manual/en/language.oop5.magic.php
And in my array it contains:
What array? That looks like a array dump of an instance of the class.
into the class global variable
What global class variable? Classes are not variables. Variables may hold references to objects, or class names.
Assuming you want to iterate through the properties of an object, and
$ressourceArray = new Server();
The code will work as expected.
If the loop is within a class method, then the loop should be....
foreach($this as $ressourceField=>$ressourceValue) {
$this->$ressourceField = $ressourceValue;
}
If you mean that you are trying to initialize the object properties from an array...
class Server {
...
function setValues($ressourceArray)
{
foreach($ressourceArray as $ressourceField=>$ressourceValue) {
$this->$ressourceField = $ressourceValue;
}
}
(BTW there's only one 's' in 'resource')
精彩评论