我最近开始使用OO PHP。作为一种训练练习,我正在尝试编写一些简单的类。我无法将变量从一个类传递到另一个类。它甚至可能吗?
class group
{
public $array = array();
public function person($name,$surname)
{
$this->person = new person($name,$surname);
}
public function __destruct()
{
print_r($this->array);
}
}
class person
{
public function __construct($name,$surname)
{
$this->name = $name;
$this->surname = $surname;
}
}
$A = new group();
$A->person("John","Doe");
我想在这里实现的是将人作为组的另一个成员(通过简单地将其放入组数组中)进行进一步修改和排序。谷歌搜索,但一无所获。
请原谅我,如果这是一个愚蠢的。 ;)
答案 0 :(得分:7)
我不确定我完全理解,但我认为你想要:
Class group {
public $members=array();
public function person($name,$surname) {
$this->members[]=new person($name,$surname);
//Creates a new person object and adds it to the internal array.
}
/*...*/
}
更好的选择(意图分离)将是:
Class group {
public $members=array();
public function addPerson(person $p) {
$this->members[]=$p;
//Avoids this function need to know how to construct a person object
// which means you can change the constructor, or add other properties
// to the person object before passing it to this group.
}
/*...*/
}
答案 1 :(得分:2)
修复正在改变
public function person($name,$surname)
{
$this->person = new person($name,$surname);
}
到
public function person($name,$surname)
{
$this->array[] = new person($name,$surname);
}
$this->person
没有存储在数组中,否则会被每次调用覆盖。
您的小组课程可以通过以下方式改进它的OO:
$array
更改为更具描述性的名称person
更改为更有意义的内容,例如add_person
答案 2 :(得分:-2)
您应该定义您的属性('name','surname')并为其提供适合性可见性
class group
{
public $array = array();
public name;
public surname;
...