Static method calling an object

Asked

Viewed 376 times

1

Because PHP allows me to use it like this, as below, the script runs normally. Wouldn’t it be incorrect? Or not? The aperador :: Isn’t it just for static methods? I was trying to access an object by a static method. But I believe I’m incorrect that way even 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;?>
  • What’s in this class Crud? It has her code?

  • Protecteds methods only

2 answers

2


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

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

If you’re using PHP version 5.4 or higher, set the bug report to allow reporting STRICT errors

One suggestion, in a development environment, it is recommended to display every kind of error and then fix every kind of problem that appears, even those of type STRICT and DEPRECATED.

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

The decision on how to set up the bug report depends on each case. There are cases where it is necessary to hide errors of type STRICT and DEPRECATED. An example, it is legacy systems where it becomes unviable to fix and convert many codes. (lack of time, lack of investments, lack of permission from a superior, etc).

Returning to the subject, it is recommended that you correct within the standard, explicitly stating the visibility and type of methods, such as the properties of a class.

Example

HOW NOT TO:

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(); will present STRICT errors and other subsequent errors such as access to $this out of context, for example. And this causes a snowball of errors.

Dribbling the bug report

As mentioned above, there may be situations where it is impracticable to correct all errors. For these cases, you can make 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 static method

class Foo {
    public function Bar() {

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

Foo::Bar2();

The problem here is it doesn’t make sense. You are just creating a faxed one to make code more "elegant" and just consuming memory and unnecessary processing.

A solution is to create definitions consistently with the ultimate goal of what needs to be used in this class.

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

  • The debug was switched off. Deprecated: Non-static method Helper::list() should not be called statically, assuming $this from incompatible context in C: wamp64 www SISGES2 system includes pagehome.php on line 103

  • taking advantage as I use an object inside the static

  • I edited it. Read "Dribbling the bug report"

  • Thank you for your attention I already use error_log and error_reporting E_ALL but I will change to that indicated thanks.

  • Friend the intention is that I have a crud class with the protected and precise methods of an external (static) method to list the categories of the database in several screens of the system and these categories are dynamic always undergoing changes. Then one method would be enough to list without having to instantiate.

  • I understand the intention but it makes no sense from the point of view OOP. Besides , class and CRUD has nothing to do with each other. But in fact, in the end it would be instantiating anyway, only in a "masked" way. I used the term "facade", and commented on redundancy and cost. There are misconceptions and nonsense in what you just commented on. Anyway, it’s not a question about design Pattern, OOP or basic modeling concepts. But as you mentioned, I had to comment briefly. If you want to learn, feel free to ask. There are several good professionals who can teach.

  • Explains the wrong concept for my learning. The crud class contains abstract, select, etc.

  • Search the site for these terms or ask specific new questions.

Show 3 more comments

1

See, as was said in Danielomine’s reply, depending on the PHP version, an error message is triggered (E_STRICT).

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

Behold:

    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 Object context

The Scope Resolution Operator (::), therefore, it should be used when you are calling static and constant methods or properties.

PHP 5.4 makes it easy for you to use methods from a class that are dynamic more easily:

It could be done like this:

 foreach ((new Helper())->lista('usuario') as $value) 
  • and if you needed to use the object of an extended class for a static method as you would use?

  • You would have to have the class instance (if the method you want to use is not static, but dynamic)

Browser other questions tagged

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