This is so wrong. My suggestion is to focus on the fundamentals, on doing the procedural very well, when you see that you need it and realize that you already know the basics so think about OOP which is less useful than speaking, even less in PHP, and more difficult than it seems. Doing OOP right is so hard to do that it usually comes out better not to use. Of course there are problems that benefit a lot from OOP and in general can be very useful when one already has enough experience in everything else.
For example, it still lacks conditions to give good names to things, which is something basic and should be mastered before doing OOP.
Almost always getters and setters is not as good an idea in PHP as it is in Java. There are even properties in PHP that would be a little better. I’ll leave it the way you want, but I already say that this is the way that almost everyone does, but it is not the most correct form. And almost everyone does it because they don’t learn properly, they’re just reproducing what others do wrong too.
It is very difficult to do OOP right without seeing the whole, without knowing every detail, without doing everything as one thing, which does not have in this code, but to take a step:
<?php
class Produto {
private $cpu;
private $mb;
private $psu;
public function __construct($cpu, $mb) {
$this->cpu = $cpu;
$this->mb = $mb;
}
function getCpu() {
return $this->cpu;
}
function setCpu($cpu) {
$this->cpu = cpu;
}
function getMb() {
return $this->mb;
}
function setMb($mb) {
$this->mb = mb;
}
}
$produto = new Produto('Core i7 7700', 'Z270');
echo $produto->getCpu();
?>
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Note that I used a builder. This is how you start an object. You don’t just have one getters and a Setter for the whole object, you have one for each attribute. If necessary. Possibly a __toString()
could be useful, among other things, but almost always people use wrong (see, and more here).
If the intention is to use the object more or less as a struct, I would remove all getters and setters and directly use the properties - which are public in that example, because declared with
var
.– bfavaretto
That’s what I’d do. I’ll fix it.
– Maniero
got it.. that’s what I was wondering. if you have a get and a set for each attribute.
– JPFreitas
@Stormwind I don’t know if I understand what you want to know.
– Maniero
@Stormwind then depends on context, correct without context is always wrong :) As I said, in PHP I would not even have a class even, if I had a reason for a class, I think the constructor would be like this, but has this example is not good to base. The right depends on many concrete factors and this is too abstract. That’s why I say everyone learns OOP wrong, everyone teaches wrong, teaches with abstract examples, then one thinks it is so. Even knowing how to do it right is hard to do it right, I miss all the time, my only advantage is that I recognize it :D
– Maniero