开发者

PHP - passing variable from one object to another troubles

开发者 https://www.devze.com 2023-03-07 20:53 出处:网络
I\'ve recently started to work with OO PHP. As a training practice I\'m trying to write some simple classes. I have trouble passing a variable from one to another class. Is it even possible?

I've recently started to work with OO PHP. As a training practice I'm trying to write some simple classes. I have trouble passing a variable from one to another class. Is it even possible?

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 =开发者_如何学JAVA $name;
        $this->surname = $surname;
    }
}

$A = new group();
$A->person("John","Doe");

What I want to archieve here is to pass person as another member of group (by simply putting it in group array) for further modifications and sorting. Been googling around but found nothing.

Please forgive me if it's a dumb one. ;)


I'm not sure I totally understand but I think you want:

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.
    }
    /*...*/
}

A better alternative (seperation of intent) would be:

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.
    }
    /*...*/
}


The fix is changing

public function person($name,$surname)
{
    $this->person = new person($name,$surname);
}

to

public function person($name,$surname)
{
    $this->array[] = new person($name,$surname);
}

$this->person is not being stored in the array otherwise, and is overwritten with each call.

Your group class could improve it's OO by:

  1. changing $array to be more descriptively named
  2. changing the function name person to something more meaningful, like add_person


You should define your properties ('name', 'surname') and give them a suitability visibility

class group
{
    public $array = array();
    public name;
    public surname;
    ...

Reference: http://php.net/manual/en/language.oop5.visibility.php

0

精彩评论

暂无评论...
验证码 换一张
取 消