A
A
Alex2018-10-10 13:32:25
PHP
Alex, 2018-10-10 13:32:25

What am I doing wrong when creating objects?

I deal with such an important concept as OOP and its application in php. I've already read the theory. But as it came to the practice that he himself came up with, he got stuck. So the essence of the problem and my solution.
There is a certain xml that stores residential complexes in itself, they are in houses, then apartments (but for now I will focus on the first one).
The structure is as follows

<complexes>
  <complex>
    <id>1</id>
    <name>ЖК 1</name>
  <complex>
  <complex>
    <id>2</id>
    <name>ЖК 2</name>
  <complex>
<complexes>

There are many more fields, but I don't need them. I wanted to collect my own object in which I will have these fields with their names of the object's properties.
I create a class "Complexes" and "Complex".
class Complexes {
  private $complexes = array();

  public function addComplex($id, $complex) {
    $this->complexes[$id] = $complex; 
  }

  public function showComplexes() {
    print_r($this);
  }
}
class Subject {
  protected $id;
  protected $name;

  function __construct($subject) {
    $this->id = $subject->id;
    $this->name = $subject->name;
  }

  public function var_d() {
    print_f($this);
  }

}

I create the "Complexes" object. Next, in the cycle, I run through the complexes, create objects (I somehow additionally process them) and add them to the "Complexes"
$complexes = new Complexes();
foreach($xml as $c => $complex) {	
  $complexObj = new Subject($complex);

  // что-то свое здесь делаю

  $complexes->addComplex($complex->id, $complexObj);
}

At the end I try to output like this
$complexes->showComplexes();
AND the array is empty
But if you put the output in the loop $complexObj->var_d(); then everything is fine, but the structure is a little strange (at least for me)
Subject Object
(
    [id:protected] => SimpleXMLElement Object
        (
            [0] => 1
        )

    [name:protected] => SimpleXMLElement Object
        (
            [0] => ЖК 1
        )
)
Subject Object
(
    [id:protected] => SimpleXMLElement Object
        (
            [0] => 2
        )

    [name:protected] => SimpleXMLElement Object
        (
            [0] => ЖК 2
        )
)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Derepko, 2018-10-10
@pilolin

$this->id   = (string) $subject->id[0];
$this->name = (string) $subject->name[0];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question