Declare public variables in the __Construct method

Asked

Viewed 988 times

3

Note the example of the method:

<?php
#noticia_construct.class.php
class Noticia{
    public $titulo; // Acredito que não seja necessário
    public $texto; // Acredito que não seja necessário
    function __construct($valor_tit, $valor_txt){
        $this -> titulo = $valor_tit;
        $this -> texto = $valor_txt;
    }
    function exibeNoticia(){
        echo "
            <center>
                <b>". $this->titulo ."</b>
                <p>". $this->texto ."</p>
            </center>
        ";
    }
}
$noticia = new Noticia('Novo curso de PHP Avançado', 'Abordaremos: POO, XML, tex.');
$noticia -> exibeNoticia();
?>

My question is about the need to declare variables as public. They are not used anywhere in the code. In other examples of the apostille the same thing happens (about classes and inheritance). If I remove this part of the code, it keeps working.

Declaring the visibility of variables is some good practice or something like that?

This is an example of Unicamp’s advanced PHP workbook.

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.

2 answers

4

Visibility

The decision whether to leave the public variable or not is the programmer according to the need. The fact that it is not used elsewhere does not mean that it cannot be used at some point. What many programmers don’t understand is that the class should be thought to be used in various situations. If you’re going to do something simple, which isn’t going to be used in many different ways and you won’t need complex maintenance, you don’t have to create a class.

The important thing is to understand why to do things. Handbooks serve to give a basis on the technique, but they do not teach people to think about problems and how to solve them.

The most common object orientation is to leave the variables private until you have a reason to make them public. But I think it is reasonable to understand that these data may be needed somewhere in isolation, especially if the class is just that, where it would be of little use. I would probably do it that way, if I were forced to create a class (this can be useful).

Doing OOP in PHP

Another important point is about methods to access class fields. Some say they should always be used. This makes some sense, but many people repeat this without knowing why it is necessary. Want to do so, ok, everyone can do as they please, but in PHP there is no need in most cases.

PHP is a language of script, the codes have Binding at runtime, so from a technical point of view it makes no difference to access the variable or a method, unless it is known that the method will need to be used in the future. Even in these cases I have my doubts if it is so useful for applications that PHP fits well (I know that many people make use of PHP where it does not fit, but there is another problem).

In most cases it is more interesting to initialize existing members with a constructor. Not always, but need to know when to use a constructor or not, can’t just follow a rule.

No longer declaring variables

If the question was about what the bfavaretto said in comment below (the AP showed that it is not), about the variable being created automatically without being declared, it is even possible, but it is not recommended, the reason to create a class is precisely to organize the code, declare what its function, its members, power is one thing, being certain is another. Some unpredictable things can happen.

In fact this is just one of the reasons I have objections to OOP in PHP, the language was not designed for this, it lets do a lot of wrong in the name of "simplicity", OOP does not go with this. In PHP an object is just a form of array associative that allows to insert and remove members at random.

I’m surprised at Unicamp teaching PHP, I hope it’s just some sort of slot machine course.

  • I think his doubt is not even that (although I agree that it should be private). It seems that he found that he can omit the declaration of the public properties, PHP creates them on the fly in the assignment. But to omit it compromises very much the clarity of the code, in my opinion.

  • @bfavaretto the comment code even induces it, but the description talks about declaring them as public since it does not use anywhere. I edited to talk about that part.

  • Sorry if I expressed myself badly, but the issue addressed is related to statement, public or private variable. But I agree that it should be declared private. .

  • @Matheusdelatorrre thank you for clarifying, the reply has information about both things, I tried to be as complete as possible giving a perspective on what should be the use with OOP and how this is not usually necessary in fact.

  • I thank @bigown!

  • @bigown this answer will find our chat from another day, leaves me thinking I’m doing everything wrong from always with PHP....

  • 3

    @Jorgeb. I can’t say this, but I think the way PHP is used is wrong in most cases. It’s not PHP’s fault! (or almost). I see very few justifications for doing complex things in PHP. You can do it, but it’s the wrong tool. If it’s simple, great! There is no point in using resources that serve to do complex things (I’m talking about OOP). There’s even some advantage to using the class, but since this was a patch, not something thought of in the language, it’s almost the same as using a array associative. I speak of this understanding the whole, the two lines of thought.

  • I’m dying to laugh at your answers, @bigown

  • @taiar but it’s serious :)

Show 4 more comments

3

Answer to the question

You are so right! If you want the variables to be really public, when using them within the class they are implicitly declared (public). This example works without errors or warnings:

<?php
  class Banana {
    public function __construct($a, $b) {
      $this->a = $a;
      $this->b = $b;
    }

    public function s() {
      echo "Digamos que {$this->a} {$this->b}.." . PHP_EOL;
    }
  }

  $a = new Banana('FORA', 'TEMER');
  $a->s();

  $a->b = "PEC 241";
  $a->s();

Note that instance variables $a and $b have not been declared and I can even update their value directly from outside the class.

Recommendations

In its code there is no need to declare the variables as public and, even, it is recommended that they be private.

In object orientation, it is not very common for you to leave public variables. Good practice is for your class to express itself through methods.

In the example you provided, it would be interesting for you to leave your variables private and create methods to access their values (called getters and setters). Follow an example:

<?php

class Noticia {

    private $titulo;
    private $texto;

    function exibeNoticia(){
        echo "
            <center>
                <b>". $this->titulo ."</b>
                <p>". $this->texto ."</p>
            </center>
        ";
    }

    public function setTitulo($titulo) {
      $this->titulo = $titulo;
    }

    public function setTexto($texto) {
      $this->texto = $texto;
    }

    public function getTitulo() {
      return $this->titulo;
    }

    public function getTexto() {
      return $this->texto;
    }
}

$noticia = new Noticia();
$noticia->setTitulo("Título da notícia");
$noticia->setTexto("Texto da notícia......");

$noticia->exibeNoticia();

This is good practice for several reasons, I will quote some of them:

  1. Decouple the class constructor: you no longer need to necessarily pass the values in the class constructor by instantiating it;
  2. Encapsulate the class data: recommend that you read more about the concept of encapsulation in object orientation. Basically, your class can do several things by setting one of its properties and the programmer who is using your class, you don’t have to worry about it.

Let’s assume that when setting the title, you always want to remove HTML characters. That way, your Setter from the title would look something like this:

    public function setTitulo($titulo) {
      $this->titulo = strip_tags($titulo);
    }

If this behavior was not encapsulated, you would need to do this routine whenever you were updating your class title field.

  • 1

    Insisting on my interpretation (see comment on the other answer), just to make it clear to those who asked: regardless of whether the property is public or private, declare it at the top of the class. If you do not declare, an implicit public property will be created at the time of attribution, and this is not clear.

  • 1

    On the getters and setters, in fact it is the recommendation. But if they don’t have any additional logic inside, I would use public property (after all why complicate?)

  • 1

    On your first comment, you are correct. I will update my response to contemplate the subject. About your second comment, the only advantage of using them is not just what I said. When you think about maintaining a large project, with well-defined Apis, it becomes essential. Then read it here: http://stackoverflow.com/a/1568230/2802720

Browser other questions tagged

You are not signed in. Login or sign up in order to post.