Doubt about attributes and methods POO in PHP

0

I'm studying PHP in PHP and I came across an example I did not understand:

The part of the code I did not understand is because the $produtos attribute is being past / calling the print () method in $produto->imprimir() and tbm $usuario->imprimir();

The example is to add in the variable $ r the output of this two sections.

How is the attribute calling the method and how does this call work?

follow the code:

<?php

class Compra {

    public $id, $produtos, $usuario;

    public function cadastrar(array $produtos, Usuario $usuario)
    {
        $this->id = rand(0, 1000);
        $this->produtos = $produtos;
        $this->usuario = $usuario;

    }

    public function imprimir()
    {
        $r = "Compra id" . $this->id . "<hr>";
        $r .= "Produtos" . "<br>"; #ESSA PARTE


        foreach ($this->produtos as $produto) {

            $r .= $produto->imprimir(); #ESSA PARTE

        }

        $r .= "<hr>";
        $r .= "Usuario" . $this->usuario->imprimir(); #ESSA PARTE

        return $r;
    }
}
    
asked by anonymous 10.09.2018 / 01:39

2 answers

2

As I understand it, the class Shopping expects an object from the class User, which must have a print method, and a collection of objects from the Product class, which must also have a print method.

<?php
class Produto
{
    public $id;

    public function imprimir()
    {
            $r = 'Eu sou o produto #' . $this->id;

            return $r;
    }
}

class Usuario
{
    public $id;

    public function imprimir()
    {
            $r = 'Eu sou o usuário #' . $this->id;

            return $r;
    }
}
?>
    
10.09.2018 / 01:48
4

Just the "print" of the last part you mentioned is a Usuario method.

Note this line:

public function cadastrar(array $produtos, Usuario $usuario)
                                           ^^^^^^^

The "register" method expects a User object.

And yet, within the method, this object is stored in the class member:

$this->usuario = $usuario;


What you are in doubt is mere unfolding:

$r .= "Usuario" . $this->usuario->imprimir(); 
//                                   ^--- método do Usuario cadastrado
//                          ^--- objeto armazenado previamente no cadastrar

The imprimir(); method of the Usuario class is called here.

The fact of having a method imprimir() in Compra is "practically" a coincidence.

It would be the case for you to take a peek at the implementation of the Usuario class to check out.

Everything here applies to Produtos too, but I imagine that at this point in the championship you have already understood. It is worth noting that although produtos is array , everything indicates that it is an array of objects of type Produto , which is dismembered in foreach : >

foreach ($this->produtos as $produto) {...
    
10.09.2018 / 01:44