Mar*_*jer 13 php yaml associative-array class object
可能重复:
将数组转换为对象PHP
我正在创建一个简单的PHP应用程序,我想使用YAML文件作为数据存储.我将获取数据作为关联数组,例如:
$user = array('username' => 'martin', 'md5password' => '5d41402abc4b2a76b9719d911017c592')
Run Code Online (Sandbox Code Playgroud)
但是,我想用一些函数扩展关联数组并使用->
运算符,所以我可以写这样的东西:
$user->username = 'martin'; // sets $user['username']
$user->setPassword('hello'); // writes md5 of 'hello' to $user['md5password']
$user->save(); // saves the data back to the file
Run Code Online (Sandbox Code Playgroud)
没有类定义,有没有一种好方法可以做到这一点?
基本上,我想在PHP中拥有JavaScript样式对象:)
FtD*_*Xw6 38
刚刚施展它:
$user = (object)$user;
Run Code Online (Sandbox Code Playgroud)
当然,还有其他更灵活的解决方案,比如创建一个实现的类ArrayAccess
:
$user = new User(); // implements ArrayAccess
echo $user['name'];
// could be the same as...
echo $user->name;
Run Code Online (Sandbox Code Playgroud)
字面上只是做一个$class = new stdClass;
迭代和重新分配.请注意,这只是一个层次,就像类型转换一样.你必须编写一个递归迭代器才能完成所有操作.从我记得Kohana 2/3有to_object()你可以使用.
找到了:
class Arr extends Kohana_Arr {
public static function to_object(array $array, $class = 'stdClass')
{
$object = new $class;
foreach ($array as $key => $value)
{
if (is_array($value))
{
// Convert the array to an object
$value = arr::to_object($value, $class);
}
// Add the value to the object
$object->{$key} = $value;
}
return $object;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28479 次 |
最近记录: |