假设我有这些课程:
abstract class AbstractEntity {
function __construct($args = array()) {
foreach ($args as $property => $value) {
$this->{$property} = $value;
}
}
public function __get( $property ) {
if( isset( $this->{$property} ) ) {
return $this->{$property};
} else {
throw new \Exception( 'Porperty ' . $property . ' not found!' );
}
}
public function __set($property, $value) {
if( isset( $this->{$property} ) ) {
$this->{$property} = $value;
} else {
throw new \Exception( 'Porperty ' . $property . ' not found!' );
}
}
}
class Person extends AbstractEntity {
protected $name;
}
class Group extends AbstractEntity {
protected $people; // array of Person
}
现在我想在循环中用$people
个对象填充Person
属性,例如:
$group = new Group( array( 'people' => array() ) );
foreach ( get_people_data() as $person_data ) {
$group->people[] = new Person( $person_data['name'] );
}
但这不起作用,我收到错误:
Notice: Indirect modification of overloaded property Group::$people has no effect in ...
我知道我可以使用临时数组,用Person
个对象填充它然后将它分配给$people
属性,但我有点不喜欢它...所以,是否有任何其他解决方案?
答案 0 :(得分:1)
尝试公开$ people属性。它适用于我的情况。
[...]
public $people = array(); // array of Person
[...]
$group->people[] = new Person( 1);
$group->people[] = new Person( 2);
答案 1 :(得分:0)
你的代码看起来有些不完整,这就是我的假设,看看它是怎么回事......
<?php
class Person {
public $name;
function __construct($n)
{
$this->name=$n;
}
}
class Group {
public $people = array(); // array of Person
}
$arr = [0=>['name'=>'John'],1=>['name'=>'Jack'],2=>['name'=>'Jill']];
$group = new Group();
foreach ($arr as $person_data ) {
$group->people[] = new Person( $person_data['name'] );
}
print_r($group->people);
<强> OUTPUT :
强>
Array
(
[0] => Person Object
(
[name] => John
)
[1] => Person Object
(
[name] => Jack
)
[2] => Person Object
(
[name] => Jill
)
)
答案 2 :(得分:0)
最后我在我的AbstractEntity
课程中添加了一个功能,允许将$value
添加到课程的$property
,该array
必须是public function append_to( $property, $value ) {
// Check that $property exists on the object and is an array
if( isset( $this->{$property} ) && is_array( $this->{$property} ) ) {
$this->{$property}[] = $value;
} else {
throw new \Exception( 'Porperty ' . $property . ' not found or is not array!' );
}
}
:
public
这些(在我看来)比其他方法有一些好处:
addPerson()
。AbstractEntity
这样的函数,所以我可以将所有类扩展{{1}}作为一组简单的属性,而不需要任何函数。