我最近开始使用 OO PHP。作为培训实践,我正在尝试编写一些简单的类(class)。我无法将变量从一个类传递到另一个类。有可能吗?
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");
我想在这里实现的是将人作为组的另一个成员传递(通过简单地将其放入组数组中)以进行进一步的修改和排序。一直在谷歌搜索,但一无所获。
如有不妥请见谅。 ;)
最佳答案
我不确定我是否完全理解,但我想你想要:
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.
}
/*...*/
}
关于PHP - 将变量从一个对象传递到另一个麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6076899/