Static method calling an object

1

Because PHP allows me to use so, as below, the script runs normally. Would not it be incorrect, or not? Is the :: adder not just for static methods? I was trying to access an object by a static method. But I think I'm incorrect in that way even though it's working.

Class Helper extends Crud
{

   public function lista($tabela)
   {
       return $this->select($tabela);
   }

}

//Uso
<?php foreach (Helper::lista('usuario') as $value):?>
  <li> <?php echo $value['usu_nome'];?></li>
<?php endforeach;?>
    
asked by anonymous 08.08.2016 / 00:56

2 answers

2

As of version 5.4, an error of type STRICT is issued for the case presented.

If you are not seeing error messages on the screen may be due to the error reporter settings.

If you are using PHP version 5.4 or higher, set the error reporter to allow reporting errors of type STRICT

A suggestion in a development environment, it is advisable to display all sorts of errors and then correct any problems that appear, even those of type STRICT and DEPRECATED.

ini_set('error_reporting', E_ALL);
ini_set('display_errors', true);

The decision on how to configure the error report depends on each case. There are cases where you need to hide STRICT and DEPRECATED errors. One example is legacy systems where becoming unworkable to fix and convert many codes. (lack of time, lack of investments, lack of permission from a superior, etc.).

Returning to the subject, we recommend that you correct within the default, explicitly declaring the visibility and type of methods, as well as the properties of a class.

Example

How NOT to do:

class Foo {
    function Bar() {

    }
}

Correct by setting the visibility. In this example we will use public .

class Foo {
    public function Bar() {

    }
}

The method is not static, so it must be invoked by an instance

$c = new Foo;
$c->Bar();

If you try Foo::Bar(); , it will display STRICT errors and other subsequent errors, such as access to $this out of context, for example. And this is causing a snowball of errors.

Dribbling the Error Reporter

As mentioned above, there may be situations where it is not feasible to correct all errors. For these cases, you can do the following configuration

/*
Aqui diz que deve reportar todos os erros exceto os do tipo STRICT e DEPRECATED.
*/
ini_set('error_reporting', E_ALL & ~E_STRICT & ~E_DEPRECATED);

/*
true: para ambiente de testes (o seu localhost)
false: para ambiente de produção (o site online, no servidor)
*/
ini_set('display_errors', false);

/*
Opcionalmente pode ligar o log de erros e então definir uma local onde deseja salvar esses avisos. 
*/
ini_set('log_errors', true);
/*
Local onde serão gerados os arquivos de logs de erro.
Apenas cuidado pois dependendo da quantidade de acessos e de erros, esses arquivos podem ficar enormes. O ideal é estarem sempre vazios. Portanto, qualquer erro pequeno, sempre corrija o mais rápido possível
*/
ini_set('error_log', BASE_DIR.'..'.DS.'logs'.DS.'php'.DS.'PHP_errors-'.date('Ym').'.log');


Gambiarra, invoking non-static method in a static method

class Foo {
    public function Bar() {

    }
    public static function Bar2() {
        $c = new Bar;
        return $c->Bar();
    }
}

Foo::Bar2();

The problem here is that it does not make sense. You are creating just one fax to make the code more "elegant" and only consuming memory and unnecessary processing.

One solution is to create the definitions consistent with the end goal of what needs to be used of this class.

Avoid gambiarras and hide errors of type STRICT and DEPRECATED. Typically, errors at this level, in the short or medium term become FATAL level.

    
08.08.2016 / 01:07
1

See, as was said in DanielOmine's response, depending on the PHP version, an error message is triggered (E_STRICT).

This is because, although it is allowed, this can generate a serious error. This is when you have the special variable $this .

See:

    class Test{

    public function z()
    {
        return 'zzz';
    }

    public function y()
    {
        $this->y = 'yyy';

        return $this->y;
    }
}


Test::z(); // Mensagem E_STRICT

Test::y(); // Aqui vai ter um problema com '$this'
  

Using this when not in context object

Scope resolution operator ( :: ), therefore, should be used when you are to call methods or static and constant properties.

PHP 5.4 provides a facility for you to use methods of a class that are dynamic with greater ease:

It could be done like this:

 foreach ((new Helper())->lista('usuario') as $value) 
    
08.08.2016 / 01:11