动态多维数组的PHP OOP问题
我对以下代码有问题:动态多维数组的PHP OOP问题,php,arrays,Php,Arrays,我对以下代码有问题: <?php class testClass { public $settings; public function __construct() { $this->settings = array( 'paths' => array( 'protocol' => 'http'
<?php
class testClass
{
public $settings;
public function __construct()
{
$this->settings = array(
'paths' => array(
'protocol' => 'http'
)
);
}
public function getSomething()
{
$string = "settings['paths']['protocol']";
echo $this->{$string}; /***** Line 19 *****/
}
}
$obj = new testClass;
$obj->getSomething(); // Outputs a 'undefined' notice
echo '<br />';
echo $obj->settings['paths']['protocol']; // Outputs http as expected
?>
如果我编写以下代码echo$obj->settings['path']['protocol']
我会得到预期的http
我不知道这为什么不起作用!!如果有人能透露一些情况,我们将不胜感激
谢谢您没有名为“
settings['path']['protocol']
”的属性。您有一个名为settings
的属性,该属性具有键路径
,该属性具有键协议
。但是PHP不像复制和粘贴代码那样解释$this->{$string}
,它查找一个名为“settings['path']['protocol']
”的属性,该属性不存在。这并不是OOP代码的特殊之处,而是任何变量的工作方式
我建议这样做:
/**
* Get settings, optionally filtered by path.
*
* @param string $path A path to a nested setting to be returned directly.
* @return mixed The requested setting, or all settings if $path is null,
* or null if the path doesn't exist.
*/
public function get($path = null) {
$value = $this->settings;
foreach (array_filter(explode('.', $path)) as $key) {
if (!is_array($value) || !isset($value[$key])) {
return null;
}
$value = $value[$key];
}
return $value;
}
这样称呼:
$obj->get('paths.protocol');
为了好玩,这里是上面的功能实现:-三,
public function get($path = null) {
return array_reduce(
array_filter(explode('.', $path)),
function ($value, $key) { return is_array($value) && isset($value[$key]) ? $value[$key] : null; },
$this->settings
);
}
你知道这类问题的解决方法吗?谢谢你的解释,我现在明白问题了!你到底想做什么?示例代码几乎没有意义,因为我想你不会真的那样使用它。非常感谢代码修复!它起作用了,帮我省去了很多压力!再次感谢。
public function get($path = null) {
return array_reduce(
array_filter(explode('.', $path)),
function ($value, $key) { return is_array($value) && isset($value[$key]) ? $value[$key] : null; },
$this->settings
);
}