How to submit attributes for extended classes?

0
class Veiculos
{
    protected $tipo = "carro";
}

Below I'm trying to identify what type of vehicle the Veiculos class has assigned. I created a tipo_veiculo function that should show the user which type of vehicle he chose and ask him to choose a color in the next step.

class Veiculo extends Veiculos
{
    public function tipo_veiculo(){
        if($tipo == "carro"){
            echo "Você selecionou carro. Escolha a cor.";
        } elseif($tipo == "moto") {
            echo "Você selecionou moto. Escolha a cor.";
        } else {
            echo "Você não selecionou nenhum carro.";
        }
    }
}

How can I send the $tipo attribute so that the Veículo class can use it? I've tried writing something using the concept of inheritance so I can try to get an answer.

    
asked by anonymous 05.01.2016 / 01:46

1 answer

4

Understanding inheritance

It is difficult to answer this question because it has a conceptual error. And if you do not understand the concepts correctly it will not code correctly.

When you inherit a class, the class that gave birth to that class becomes part of it, put it together. That is, the daughter class is all that the parent class is, plus something. They are not two separate things that can communicate (send). It's one thing.

It's already weird a class Veiculo inherit from a class called Veiculos . I have already said another question that there has to be a reason to use a class and still more to use inheritance. Almost nothing needs inheritance. Inheritance must be the exception, even the most fanatical about OOP know of it nowadays.

One of the most important things in coding is giving good names to things. Does a thing that calls Veiculos have multiple vehicles inside it? Does this class have? Does not appear. And if it is a thing that has multiple vehicles, why would it be part of a single vehicle? Are you going to put several vehicles inside a vehicle? It does not make sense.

If this class is a part of a vehicle, then it should have another name. And if it's only a part, there should be composition and no inheritance ( see here too ). I just can not imagine how the inheritance is appropriate in this case.

The specific problem

Having said all that is important for anyone who wants to learn from this question, just access the variable the right way. After all $tipo is a local variable (of the function), since $this->tipo is the instance variable of the class. The error is different from what is described in the question.

See running on ideone .

    
05.01.2016 / 02:18