0
I am following an OO study book and I came across a problem related to a method call. I will contextualize with the Classes.
<?php
class Orcamento{
private $itens;
public function adicionar(Produto $produto, $qtde){
$this->itens[] = array($qtde, $produto);
}
public function calculaTotal(){
$total = 0;
foreach ($this->itens as $item) {
// echo "<pre>";print_r($item[0]);die();
echo "<pre>";print_r($item[1]);die();
// echo "<pre>";var_dump($item[1]->getPreco());die();
$total +=($item[0] * $item[1]->getPreco());
}
// die($total);
return $total;
}
}
?>
<?php
class Produto{
private $descricao;
private $estoque;
private $preco;
public function __construct($descricao, $estoque, $preco){
$this->$descricao = $descricao;
$this->$estoque = $estoque;
$this->$preco = $preco;
}
public function getPreco(){
return $this->preco;
}
}
?>
Cria Orçamento
$orcamento = new Orcamento();
$orcamento->adicionar( new Produto('Maquina de café', 10, 299), 1);
$orcamento->adicionar( new Produto('Mesa de vido', 10, 170), 1);
$orcamento->adicionar( new Produto('Barra de chocolate', 10, 7), 3);
// echo "<pre>";print_r($orcamento);die();
print $orcamento->calculaTotal();
?>
It is an example using aggregation the problem is that whenever the getPreco method is called the same does not return anything. The strangest thing about executing the die is that the Object has all the right Attributes (quantity and price). So much so that when running the die on line 16 of the file Orcamento.php the return is this :
Produto Object
(
[descricao:Produto:private] =>
[estoque:Produto:private] =>
[preco:Produto:private] =>
[Maquina de café] => Maquina de café
[10] => 10
[299] => 299
)
Now I don’t know if it’s a syntax error or a structure error.
$this->$preco = $preco
, there is no this $ before price, it should be$this->preco = $preco
– Woss
just as @Andersoncarloswoss said, you have the same reptindo error here
$this->$descricao = $descricao; $this->$estoque = $estoque; $this->$preco = $preco;
, after the->
doesn’t have the$
, that explains why these values are empty– Wees Smith