将 PHP 数组转换为类变量 [英] Converting a PHP array to class variables
问题描述
简单的问题,如何将关联数组转换为类中的变量?我知道有强制转换来做一个 (object) $myarray
或任何它是什么,但这将创建一个新的 stdClass 并且对我没有多大帮助.是否有任何简单的一两行方法可以使每个 $key =>;将数组中的 $value
配对为我的班级的 $key = $value
变量?我认为为此使用 foreach 循环不太合乎逻辑,我最好将其转换为 stdClass 并将其存储在变量中,不是吗?
Simple question, how do I convert an associative array to variables in a class? I know there is casting to do an (object) $myarray
or whatever it is, but that will create a new stdClass and doesn't help me much. Are there any easy one or two line methods to make each $key => $value
pair in my array into a $key = $value
variable for my class? I don't find it very logical to use a foreach loop for this, I'd be better off just converting it to a stdClass and storing that in a variable, wouldn't I?
class MyClass {
var $myvar; // I want variables like this, so they can be references as $this->myvar
function __construct($myarray) {
// a function to put my array into variables
}
}
推荐答案
这个简单的代码应该可以工作:
This simple code should work:
<?php
class MyClass {
public function __construct(Array $properties=array()){
foreach($properties as $key => $value){
$this->{$key} = $value;
}
}
}
?>
示例用法
$foo = new MyClass(array("hello" => "world"));
$foo->hello // => "world"
<小时>
或者,这可能是更好的方法
Alternatively, this might be a better approach
<?php
class MyClass {
private $_data;
public function __construct(Array $properties=array()){
$this->_data = $properties;
}
// magic methods!
public function __set($property, $value){
return $this->_data[$property] = $value;
}
public function __get($property){
return array_key_exists($property, $this->_data)
? $this->_data[$property]
: null
;
}
}
?>
用法相同
// init
$foo = new MyClass(array("hello" => "world"));
$foo->hello; // => "world"
// set: this calls __set()
$foo->invader = "zim";
// get: this calls __get()
$foo->invader; // => "zim"
// attempt to get a data[key] that isn't set
$foo->invalid; // => null
这篇关于将 PHP 数组转换为类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!