p1ratrulezzz / lazyaccess
提供对数组元素的 LazyAccess 功能
2.0.3
2020-10-06 12:11 UTC
Requires
- php: >=5.3.2
This package is auto-updated.
Last update: 2024-09-06 21:13:44 UTC
README
LazyAccess 是围绕任何数组的包装器。提供了一种轻松获取其值或获取默认值的方法。
替换愚蠢的长构造,例如
isset($var) ? $var : NULL.
安装
使用 composer
更新您的 composer.json 为以下内容
require: { "p1ratrulezzz/lazyaccess": "master" }
并运行
composer install
或(推荐)
composer require p1ratrulezzz/lazyaccess master
第二种方法将允许您在不手动更改 composer.lock 文件的情况下安装此包。
手动安装
git clone --branch master https://github.com/p1ratrulezzz/LazyAccess-to-PHP-arrays.git lazyaccess
然后在 PHP 代码中包含以下文件
require_once 'lazyaccess/src/LazyAccess.php'; require_once 'lazyaccess/src/LazyAccessTyped.php';
描述
例如:普通的 PHP 代码是
$somevar = isset($array[$key]['key2'][0]) ? $array[$key]['key2'][0] : 'some_default_value';
此代码很长且重复相同的内容。使用 LazyAccess,相同的代码将是
$wrapper = new LazyAccessTyped($array); //Define it once somewhere in your code $somevar = $array[$key]->key2[0]->value('some_default_value'); //or $somevar = $array[$key]['key2'][0]->value('some_default_value'); //the same as the above //or $somevar = $array->$key->key2->0->value('some_default_value'); //the same as the above // Also there are some wrappers with types: asString(), asInteger(), asDouble() $somevar = $array->{$key}->key2->0->asString('some_default_value'); $somevar = $array->{$key}->key2->0->asInteger(0); // It will perform intval() operation before returning, so you can be sure that there will be an integer value. // asDouble() also will replace comma "," to a point ".", for example value 1,93 will be converted to 1.93 $floating_point_value = new LazyAccessTyped(['test_float' => ['inner' => '1,93']])->test_float->inner->asDouble(0); // Will return 1.93
它提供了使用数组运算符("[]")或对象运算符("->")来访问嵌套数组元素的能力!
注意
有两个类:LazyAccess 和 LazyAccessTyped。LazyAccessTyped 提供了使用转换器(如 asFloat()、asInteger() 等)的能力。
请勿使用 LazyAccess,因为它可能对返回值产生不可预测的行为。LazyAccessTyped 更好且更安全。