我有这个代码:
class Foo {
public $bar = array();
}
$foo = new Foo();
$foo -> bar['count'] = 100;
echo $foo -> bar['count']; // 100
$prop = 'bar';
echo $foo -> $prop['count']; // Warning: Illegal string offset 'count'
这给了我这个错误:
为什么?以及如何让它发挥作用?Warning: Illegal string offset 'count' in ...
====================
我想要这个的原因是:
class Foo {
private $data1 = array();
private $data2 = array();
public function loadData1(array $data) {
return $this -> loadDataInProperty($data, 'data1');
}
public function loadData2(array $data) {
return $this -> loadDataInProperty($data, 'data2');
}
private function loadDataInProperty(array $data, $prop) {
// Filtering, etc.
foreach ($data as $key => $value) {
// Keys comparison, etc.
$this -> $prop[$key] = $value;
}
}
}
基本上,我想将一些数据加载到对象的属性(数组)之一中。有很多不同的数据集。有更好/更酷的方法来实现这一目标吗?
最佳答案
试试这个:
<?php
class Foo {
public $bar = array();
}
$foo = new Foo();
$foo -> bar['count'] = 100;
echo $foo -> bar['count']; // 100
$prop = 'bar';
echo $foo -> {$prop}['count']; // Warning: Illegal string offset 'count'
关于php - "Illegal string offset"对象属性数组警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28018815/