Declare public variables in the __construct

3

Look at the example 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 handbook the same thing happens (about classes and inheritance). If I take this part of the code, it keeps running.

Declare visibility to variables is any good practice or something similar?

This is an example of the advanced PHP tutorial from Unicamp.

    
asked by anonymous 02.11.2016 / 19:02

2 answers

4

Visibility

The decision whether to leave the variable public or not is the programmer's according to need. Not using it elsewhere does not mean it can not be used at some point. What a lot of programmer does not understand is that the class should be thought to be used in a variety of situations. If it is to do something simple, it will not be used in many ways and it will not require complex maintenance, you do not have to create a class. The important thing is to understand why doing things. Handouts serve to provide a basis for technique, but they do not teach people how to think about problems and how to solve them.

The most common object-orientation is to leave variables private until you have a reason to make them public. But I find it reasonable to understand that such 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 to create a class ( this might be useful ).

Making OOP in PHP

Another important point is about methods to access the fields of the class. Some say that they should always be used. This makes up some sense, but many people repeat it without knowing why it is needed. Want to do so, okay, everyone can do as they please, but in PHP there is no need in most cases. PHP is a script language, 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 those cases I have my doubts if it is so useful for applications that PHP fits well (I know a lot of people make use of PHP where it does not fit, but there the problem is otherwise).

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

Stop 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 possible, but not recommended, the reason for creating a class it is precisely to organize the code, to declare what its function, its members, power is one thing, to be certain is another. Some unpredictable things can happen.

Actually this is just one of the reasons I have objections to OOP in PHP, the language was not intended for this, it leaves do much wrong in the name of "simplicity", OOP does not match that. In PHP an object is just an associative array that allows you to insert and remove members at random.

I'm amazed at Unicamp teaching PHP, hopefully it's just some nickel-plating course.

    
02.11.2016 / 19:28
3

Answer to question

You're correct! If you want the variables to be even public, when using them within the class they are declared implicitly (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();

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

Recommendations

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

In object-oriented, it is not very common for you to leave public variables. The 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). Here is 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 a good practice for several reasons, I will cite some of them:

  • Decouple the constructor of the class: you no longer need to necessarily pass the values in the class constructor, when instantiating it;
  • Encapsulates class data: I encourage you to read more about the concept of object-oriented encapsulation. Basically, your class can do several things by setting one of its properties and the programmer who is using your class, you do not have to worry about it.
  • Let's assume that when you set the title, you always want to remove HTML characters. This way, your title setter 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 to update the title field of your class.

        
    02.11.2016 / 21:04