Calling protected variable inside static method

Asked

Viewed 505 times

4

<?php

     class Foo{

          protected $calc;

          function __construct(){
               $this->calc = 2;
          }

          public static function getCalc(){
               return $this->calc * 5;
          }
     }
     Foo::getCalc();

When I spin, he gives me that mistake:

Fatal error: Using $this when not in Object context in...

Why can’t I call a variable protected within a function defined as static?

  • 3

    Because the variable does not exist in the static scope. Understand that nonstatic variables only come into existence when the class object is created, hence the error. To use the variable, VC first needs to create a Foo object.

  • 3

    The problem is not protected but the fact that you manipulate an instance attribute in a static method, it belongs to the class and not to the object, then access it to the $this is not valid.

  • Right, and what would be the solution to that? Change statics to public?

  • This code seems to be an example just ... doesn’t it do much ... the purpose of the method being static is to save the creation of an object? can solve this with a fixed value or a constant.

2 answers

6


Think of all static members as a single instance pre-instantiated in the application, it’s as if these members belong to another object.

Already the members considered of instance belong each to its own instance (can be a variable). There is no way to mix them, deep down they are very different things in different memory places with different roles.

Even if I try, which $this are we talking? This is a variable that stores the instance, the language does not know which object is talking about in the code, after all there is accessing something that is not of any normal instance.

  • 1

    even if you use self:: the protected attribute would also have to be static?

  • It is not possible to be static and protected at the same time. Being static prevents inheritance from happening, so it makes no sense.

0

Unable to access class attributes or other methods within a static method. Static methods are not in the context of the object.

Browser other questions tagged

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